import { Controller, Get, Param, Delete, 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';

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

  @Get()
  @ApiOperation({ summary: '知识库列表（管理员，支持搜索）' })
  async list(
    @Query('page') page = '1',
    @Query('limit') limit = '20',
    @Query('search') search?: string,
  ) {
    const p = parseInt(page), l = parseInt(limit);
    const where: any = { deletedAt: null };
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { id: { contains: search } },
        { user: { email: { contains: search } } },
        { user: { nickname: { contains: search } } },
      ];
    }
    const [items, total] = await Promise.all([
      this.prisma.knowledgeBase.findMany({
        where,
        orderBy: { updatedAt: 'desc' },
        skip: (p - 1) * l, take: l,
        include: { user: { select: { nickname: true, email: true } } },
      }),
      this.prisma.knowledgeBase.count({ where }),
    ]);
    const enriched = await enrichWithNames(this.prisma, items);
    return { items: enriched, total, page: p, limit: l, totalPages: Math.ceil(total / l) };
  }

  // ══ All Sources (must be before :id to avoid route conflict) ══

  @Get('all-sources')
  @ApiOperation({ summary: '所有资料来源列表（管理员全局视图）' })
  async allSources(
    @Query('page') page = '1',
    @Query('limit') limit = '20',
    @Query('knowledgeBaseId') kbId?: string,
    @Query('parseStatus') parseStatus?: string,
    @Query('search') search?: string,
  ) {
    const p = parseInt(page), l = parseInt(limit);
    const where: any = { deletedAt: null };
    if (kbId) where.knowledgeBaseId = kbId;
    if (parseStatus) where.parseStatus = parseStatus;
    if (search) where.originalFilename = { contains: search };

    const [items, total] = await Promise.all([
      this.prisma.knowledgeSource.findMany({ where, orderBy: { createdAt: 'desc' }, skip: (p - 1) * l, take: l }),
      this.prisma.knowledgeSource.count({ where }),
    ]);
    const enriched = await enrichWithNames(this.prisma, items);
    return { items: enriched, total, page: p, limit: l, totalPages: Math.ceil(total / l) };
  }

  @Get(':id')
  @ApiOperation({ summary: '知识库详情' })
  async detail(@Param('id') id: string) {
    const kb = await this.prisma.knowledgeBase.findUnique({
      where: { id },
      include: {
        user: { select: { nickname: true, email: true } },
        sources: { where: { deletedAt: null }, take: 20 },
        _count: { select: { items: true } },
      },
    });
    return kb;
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除知识库' })
  async remove(@Param('id') id: string) {
    await this.prisma.knowledgeBase.update({ where: { id }, data: { deletedAt: new Date() } });
    return { success: true };
  }

  @Get(':id/sources')
  @ApiOperation({ summary: '知识库资料来源列表' })
  async sources(@Param('id') id: string) {
    return this.prisma.knowledgeSource.findMany({
      where: { knowledgeBaseId: id, deletedAt: null },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });
  }

  @Get('sources/:sourceId/references')
  @ApiOperation({ summary: 'Source 引用追踪' })
  async sourceReferences(@Param('sourceId') sourceId: string) {
    return this.prisma.sourceReference.findMany({
      where: { sourceId },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });
  }

  // ── Candidates ──

  @Get('candidates')
  @ApiOperation({ summary: '候选知识点列表' })
  async candidates(@Query('status') status?: string, @Query('kbId') kbId?: string) {
    const where: any = {};
    if (status) where.status = status;
    if (kbId) where.knowledgeBaseId = kbId;
    return this.prisma.importCandidate.findMany({ where, orderBy: { createdAt: 'desc' }, take: 100 });
  }

  // ── Knowledge items ──

  @Get('items')
  @ApiOperation({ summary: '知识点列表（管理员）' })
  async items(@Query('kbId') kbId?: string, @Query('limit') limit = '50') {
    const where: any = { deletedAt: null };
    if (kbId) where.knowledgeBaseId = kbId;
    return this.prisma.knowledgeItem.findMany({ where, orderBy: { createdAt: 'desc' }, take: parseInt(limit) });
  }

  // ── Chunks ──

  @Get('chunks')
  @ApiOperation({ summary: 'Chunk 列表（按 Source）' })
  async chunks(@Query('sourceId') sourceId?: string, @Query('limit') limit = '50') {
    const where: any = { deletedAt: null };
    if (sourceId) where.sourceId = sourceId;
    return this.prisma.knowledgeChunk.findMany({ where, orderBy: { chunkIndex: 'asc' }, take: parseInt(limit) });
  }
}
