import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } 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';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import type { AdminRole } from '../../common/types/admin-role.enum';

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

  @Get('sessions')
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '用户对话列表' })
  async sessions(@Query('userId') userId?: string) {
    const items = await this.prisma.chatSession.findMany({
      where: userId ? { userId } : undefined,
      orderBy: { updatedAt: 'desc' },
      take: 100,
      include: { _count: { select: { messages: true } } },
    });
    return enrichWithNames(this.prisma, items);
  }

  @Get('sessions/:id/messages')
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '对话消息详情' })
  async messages(@Param('id') id: string) {
    return this.prisma.chatMessage.findMany({
      where: { sessionId: id },
      orderBy: { createdAt: 'asc' },
      include: { citations: true },
    });
  }
}
