import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { AdminGuard } from './admin.guard';
import { PrismaService } from '../../prisma/prisma.service';

@ApiTags('管理后台 - 运营管理')
@Controller('admin')
@UseGuards(AuthGuard('jwt'), AdminGuard)
@ApiBearerAuth()
export class OperationsController {
  constructor(private prisma: PrismaService) {}

  // Banners
  @Get('banners')
  async banners() {
    return { items: await this.prisma.banner.findMany({ orderBy: { sortOrder: 'asc' } }) };
  }

  @Post('banners')
  async createBanner(@Body() body: { title: string; image: string; link?: string; position?: string; sortOrder?: number; status?: string }) {
    return this.prisma.banner.create({
      data: {
        title: body.title,
        image: body.image,
        link: body.link || '',
        position: body.position || 'home',
        sortOrder: body.sortOrder || 0,
        status: body.status || 'DRAFT',
      },
    });
  }

  @Put('banners/:id')
  async updateBanner(@Param('id') id: string, @Body() body: any) {
    return this.prisma.banner.update({ where: { id: parseInt(id) }, data: body });
  }

  @Delete('banners/:id')
  async deleteBanner(@Param('id') id: string) {
    return this.prisma.banner.delete({ where: { id: parseInt(id) } });
  }

  // Notifications
  @Get('notifications')
  async notifications() {
    return { items: await this.prisma.systemNotification.findMany({ orderBy: { createdAt: 'desc' } }) };
  }

  @Post('notifications')
  async createNotification(@Body() body: { title: string; content: string; type?: string; target?: string; status?: string }) {
    return this.prisma.systemNotification.create({
      data: {
        title: body.title,
        content: body.content,
        type: body.type || 'system',
        target: body.target || 'all',
        status: body.status || 'DRAFT',
        sentAt: body.status === 'SENT' ? new Date() : null,
      },
    });
  }

  @Delete('notifications/:id')
  async deleteNotification(@Param('id') id: string) {
    return this.prisma.systemNotification.delete({ where: { id: parseInt(id) } });
  }

  // Config
  @Get('config')
  async configs() {
    return { items: await this.prisma.systemConfig.findMany() };
  }

  @Get('config/:category')
  async configByCategory(@Param('category') category: string) {
    return { items: await this.prisma.systemConfig.findMany({ where: { category } }) };
  }

  // Content status toggles (for admin list pages)
  @Put('courses/:id/status')
  async toggleCourseStatus(@Param('id') id: string, @Body() body: { status: string }) {
    return this.prisma.course.update({ where: { id: parseInt(id) }, data: { status: body.status as any } });
  }

  @Put('contents/:id/status')
  async toggleContentStatus(@Param('id') id: string, @Body() body: { status: string }) {
    return this.prisma.content.update({ where: { id: parseInt(id) }, data: { status: body.status as any } });
  }

  @Put('prompts/:id/status')
  async togglePromptStatus(@Param('id') id: string, @Body() body: { status: string }) {
    return this.prisma.prompt.update({ where: { id: parseInt(id) }, data: { status: body.status as any } });
  }

  @Put('tools/:id/status')
  async toggleToolStatus(@Param('id') id: string, @Body() body: { status: string }) {
    return this.prisma.tool.update({ where: { id: parseInt(id) }, data: { status: body.status as any } });
  }

  // Comments
  @Get('comments')
  async comments(@Query('status') status?: string) {
    const where: any = {};
    if (status) where.status = status;
    return { items: await this.prisma.comment.findMany({ where, orderBy: { createdAt: 'desc' }, include: { user: { select: { id: true, nickname: true } }, post: { select: { id: true, title: true } } } }) };
  }

  @Put('config/:key')
  async updateConfig(@Param('key') key: string, @Body() body: { value: string; description?: string; category?: string }) {
    const existing = await this.prisma.systemConfig.findUnique({ where: { key } });
    if (existing) {
      return this.prisma.systemConfig.update({ where: { key }, data: { value: body.value, ...(body.description !== undefined ? { description: body.description } : {}) } });
    }
    return this.prisma.systemConfig.create({
      data: { key, value: body.value, category: body.category || 'other', description: body.description || '' },
    });
  }

  @Delete('config/:key')
  async deleteConfig(@Param('key') key: string) {
    return this.prisma.systemConfig.delete({ where: { key } });
  }
}