import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger, Inject } from '@nestjs/common';
import type { Job } from 'bullmq';
import {
  QUEUE_AI_BACKGROUND,
} from '../infrastructure/queue/queue.service';
import { workerOptionsFor } from '../infrastructure/queue/queue-definitions';
import {
  AI_JOB_EXECUTION_ENGINE,
} from '../modules/ai-job/ai-job-execution-engine.interface';

/**
 * M-AI-03-05: AiBackgroundJobWorker
 *
 * 薄 Processor — 职责仅限于：
 *   1. 接收 BullMQ Job（payload 仅含 `{ jobId }`）
 *   2. 注入 AiJobExecutionEngine
 *   3. 调用 engine.execute(jobId, context)
 *
 * 禁止在 Processor 中：读取 Prompt、调用 Provider、写业务表、
 * 实现状态机、实现 Job Type switch。
 */
@Processor(QUEUE_AI_BACKGROUND, workerOptionsFor(QUEUE_AI_BACKGROUND))
export class AiBackgroundJobWorker extends WorkerHost {
  private readonly logger = new Logger(AiBackgroundJobWorker.name);

  constructor(
    @Inject(AI_JOB_EXECUTION_ENGINE)
    private readonly engine: any,
  ) {
    super();
    // P2-06: Engine 是硬依赖。DI 解析失败 → Worker 启动 crash（fail-fast）。
  }

  async process(job: Job<{ jobId: string }>): Promise<void> {
    const { jobId } = job.data;

    if (!jobId) {
      this.logger.error(`Invalid job payload: missing jobId`);
      throw new Error('Invalid job payload: missing jobId');
    }

    const context = {
      jobId: job.id ?? '',
      attemptMade: job.attemptsMade,
      updateProgress: async (progress: number) => {
        await job.updateProgress(progress);
      },
    };

    await this.engine.execute(jobId, context);
  }
}
