import { Controller, Get, Query } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { PrismaService } from '../../prisma/prisma.service';

@ApiTags('Public')
@Controller('public')
export class PublicController {
  constructor(private prisma: PrismaService) {}

  @Get('stats')
  async getStats() {
    const [courses, prompts, tools, users] = await Promise.all([
      this.prisma.course.count({ where: { status: 'PUBLISHED', deletedAt: null } }),
      this.prisma.prompt.count({ where: { status: 'PUBLISHED' } }),
      this.prisma.tool.count({ where: { status: 'PUBLISHED' } }),
      this.prisma.user.count({ where: { status: 'ACTIVE' } }),
    ]);
    return { courses, prompts, tools, users };
  }

  @Get('banners')
  async banners(@Query('position') position?: string) {
    const now = new Date();
    const where: any = {
      status: { not: 'DRAFT' },
      AND: [
        { OR: [{ startAt: null }, { startAt: { lte: now } }] },
        { OR: [{ endAt: null }, { endAt: { gte: now } }] },
      ],
    };
    if (position) where.position = position;
    const items = await this.prisma.banner.findMany({ where, orderBy: { sortOrder: 'asc' } });
    return { items };
  }

  @Get('config')
  async getConfig() {
    const configs = await this.prisma.systemConfig.findMany({ where: { status: 'ACTIVE' } });
    const result: Record<string, string> = {};
    for (const c of configs) result[c.key] = c.value;
    return result;
  }

  @Get('models')
  async getModels() {
    const items = await this.prisma.aiModel.findMany({ where: { status: 'ACTIVE' }, orderBy: { sortOrder: 'asc' } });
    return { items: items.map(m => ({ id: m.id, name: m.name, provider: m.provider, description: m.description, capabilities: m.capabilities, pricing: m.pricing, isFree: m.isFree })) };
  }
}
