import { Controller, Get, Delete, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { enrichWithNames } from '../../common/helpers/name-resolver';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import type { AdminRole } from '../../common/types/admin-role.enum';
import { FilesService } from './files.service';

@ApiTags('admin-files')
@Controller('admin-api/files')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
@ApiBearerAuth()
export class AdminFilesController {
  constructor(private readonly prisma: PrismaService, private readonly filesService: FilesService) {}

  @Get()
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '文件列表（管理员）' })
  async list(@Query('page') page = '1', @Query('limit') limit = '20') {
    const p = parseInt(page), l = parseInt(limit);
    const [items, total] = await Promise.all([
      this.prisma.uploadedFile.findMany({
        where: {},
        orderBy: { createdAt: 'desc' },
        skip: (p - 1) * l, take: l,
        include: { user: { select: { nickname: true, email: true } } },
      }),
      this.prisma.uploadedFile.count({ where: {} }),
    ]);
    const enriched = await enrichWithNames(this.prisma, items); return { items: enriched, total, page: p, limit: l, totalPages: Math.ceil(total / l)  };
  }

  @Delete(':id')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '软删除文件' })
  async remove(@Param('id') id: string) {
    return this.filesService.deleteFileAsAdmin(id);
  }
}
