import { Controller, Get, Post, Param, Query, Body, UseGuards, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
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 { AiJobService } from './ai-job.service';

@ApiTags('admin-ai-jobs')
@Controller('admin-api/ai/jobs')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
@ApiBearerAuth()
export class AiJobAdminController {
  constructor(
    private readonly service: AiJobService,
    @InjectQueue('ai-interactive') private readonly aiInteractiveQ: Queue,
    @InjectQueue('ai-background') private readonly aiBackgroundQ: Queue,
  ) {}

  @Get()
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'Job 列表' })
  async list(
    @Query('jobType') jobType?: string,
    @Query('lifecycleStatus') status?: string,
    @Query('queueName') queueName?: string,
    @Query('userId') userId?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    return this.service.listJobs({
      jobType, lifecycleStatus: status, queueName, userId,
      page: page ? parseInt(page) : undefined,
      limit: limit ? parseInt(limit) : undefined,
    });
  }

  @Get(':jobId')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'Job 详情（含 Snapshot/Outbox/UsageLog）' })
  async detail(@Param('jobId') jobId: string) {
    return this.service.getJobDetail(jobId);
  }

  @Post(':jobId/retry')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'Admin 重试（创建新 Job，parentJobId 关联原 Job）' })
  async retry(@Param('jobId') jobId: string, @Query('operationId') operationId: string) {
    if (!operationId || operationId.trim().length === 0) {
      throw new BadRequestException('operationId is required for Admin retry');
    }
    if (operationId.length > 128 || !operationId.match(/^[a-zA-Z0-9_-]+$/)) {
      throw new BadRequestException('operationId must be 1-128 alphanumeric chars, hyphens, or underscores');
    }
    return this.service.retryJob('admin', jobId, operationId.trim());
  }

  @Get('queues/status')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '队列状态（ai-interactive / ai-background）' })
  async queueStatus() {
    const [iw, ia, ic, ifa, id, bw, ba, bc, bf, bd] = await Promise.all([
      this.aiInteractiveQ.getWaitingCount(), this.aiInteractiveQ.getActiveCount(),
      this.aiInteractiveQ.getCompletedCount(), this.aiInteractiveQ.getFailedCount(),
      this.aiInteractiveQ.getDelayedCount(),
      this.aiBackgroundQ.getWaitingCount(), this.aiBackgroundQ.getActiveCount(),
      this.aiBackgroundQ.getCompletedCount(), this.aiBackgroundQ.getFailedCount(),
      this.aiBackgroundQ.getDelayedCount(),
    ]);
    return {
      'ai-interactive': { waiting: iw, active: ia, completed: ic, failed: ifa, delayed: id },
      'ai-background': { waiting: bw, active: ba, completed: bc, failed: bf, delayed: bd },
    };
  }

  @Get('outbox/status')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'Outbox 状态' })
  async outboxStatus() {
    return this.service.getOutboxStatus();
  }
}
