import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { enrichWithNames } from '../../common/helpers/name-resolver';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';

@ApiTags('admin-review')
@ApiBearerAuth()
@Controller('admin-api/reviews')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
export class AdminReviewController {
  constructor(private readonly prisma: PrismaService) {}

  @Get()
  @ApiOperation({ summary: '复习卡片列表（Admin）' })
  @ApiQuery({ name: 'search', required: false })
  @ApiQuery({ name: 'status', required: false })
  @ApiQuery({ name: 'page', required: false })
  @ApiQuery({ name: 'limit', required: false })
  async list(
    @Query('search') search?: string,
    @Query('status') status?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const take = Math.min(Number(limit) || 20, 100);
    const skip = (Math.max(Number(page) || 1, 1) - 1) * take;
    const where: any = {};
    if (status) where.status = status;
    if (search) {
      where.frontText = { contains: search };
    }

    const select = {
      id: true, userId: true, frontText: true, difficulty: true,
      status: true, scheduleState: true, intervalDays: true,
      repetitionCount: true, lapseCount: true, nextReviewAt: true,
    };

    const [items, total] = await Promise.all([
      this.prisma.reviewCard.findMany({
        where, orderBy: { createdAt: 'desc' }, take, skip, select,
      }),
      this.prisma.reviewCard.count({ where }),
    ]);

    const enriched = await enrichWithNames(this.prisma, items);
    return { items: enriched, total };
  }
}
