import { Controller, Get, Post, Param, Query, Body, UseGuards, BadRequestException } 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';

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

  @Get()
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '导入任务列表' })
  async list(
    @Query('page') page = '1',
    @Query('limit') limit = '20',
    @Query('status') status?: string,
    @Query('kbId') kbId?: string,
    @Query('sortBy') sortBy?: string,
    @Query('sortOrder') sortOrder?: string,
  ) {
    const p = parseInt(page), l = parseInt(limit);
    const where: any = {};
    if (status) where.status = status;
    if (kbId) where.knowledgeBaseId = kbId;

    // 排序：默认按创建时间倒序
    const orderBy: any = {};
    const allowedSortFields = ['sourceName', 'createdAt', 'status', 'sourceType', 'progress', 'retryCount'];
    const field = allowedSortFields.includes(sortBy || '') ? sortBy! : 'createdAt';
    const dir = sortOrder === 'ascend' ? 'asc' : 'desc';
    orderBy[field] = dir;

    const [items, total] = await Promise.all([
      this.prisma.documentImport.findMany({ where, orderBy, skip: (p - 1) * l, take: l }),
      this.prisma.documentImport.count({ where }),
    ]);

    // 批量查询 source 是否存在（排除软删除）
    const sourceIds = [...new Set(items.map(i => i.sourceId).filter(Boolean))] as string[];
    const existingSourceIds = new Set(
      sourceIds.length > 0
        ? (await this.prisma.knowledgeSource.findMany({
            where: { id: { in: sourceIds }, deletedAt: null },
            select: { id: true },
          })).map(s => s.id)
        : [],
    );

    const enriched = await enrichWithNames(this.prisma, items);
    const itemsWithSourceStatus = enriched.map((item: any) => ({
      ...item,
      sourceDeleted: !!item.sourceId && !existingSourceIds.has(item.sourceId),
    }));
    return { items: itemsWithSourceStatus, total, page: p, limit: l, totalPages: Math.ceil(total / l) };
  }

  @Get(':id')
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '导入任务详情' })
  async detail(@Param('id') id: string) {
    const [job, steps] = await Promise.all([
      this.prisma.documentImport.findUnique({ where: { id } }),
      this.prisma.importStepLog.findMany({ where: { importId: id }, orderBy: { createdAt: 'asc' } }),
    ]);
    return { job, steps };
  }

  @Post(':id/retry')
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '重试失败导入' })
  async retry(@Param('id') id: string) {
    const job = await this.prisma.documentImport.findUnique({ where: { id } });
    if (!job) throw new BadRequestException('导入任务不存在');

    // 检查 source 是否存在（排除软删除）
    if (job.sourceId) {
      const source = await this.prisma.knowledgeSource.findFirst({
        where: { id: job.sourceId, deletedAt: null },
      });
      if (!source) {
        throw new BadRequestException('关联的资料来源已删除，无法重新解析。请删除此导入记录后重新上传文件。');
      }
    }

    await this.prisma.documentImport.update({
      where: { id },
      data: { status: 'QUEUED', retryCount: 0, errorMessage: null },
    });
    return { success: true };
  }

  @Post('batch-retry')
  @AdminRoles('ADMIN' as AdminRole)
  @ApiOperation({ summary: '批量重新解析' })
  async batchRetry(@Body() body: { ids: string[] }) {
    if (!body.ids || body.ids.length === 0) {
      throw new BadRequestException('请选择至少一个导入任务');
    }

    const jobs = await this.prisma.documentImport.findMany({
      where: { id: { in: body.ids } },
      select: { id: true, sourceId: true, sourceName: true },
    });

    const skipped: string[] = [];
    const updated: string[] = [];

    for (const id of body.ids) {
      const job = jobs.find(j => j.id === id);
      if (!job) continue;

      // 检查 source 是否存在（排除软删除）
      if (job.sourceId) {
        const source = await this.prisma.knowledgeSource.findFirst({
          where: { id: job.sourceId, deletedAt: null },
        });
        if (!source) {
          skipped.push(job.sourceName || id);
          continue;
        }
      }

      await this.prisma.documentImport.update({
        where: { id },
        data: { status: 'QUEUED', retryCount: 0, errorMessage: null },
      });
      updated.push(id);
    }

    return { success: true, updated: updated.length, skipped, skippedCount: skipped.length };
  }
}
