import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { JobDefinitionRegistry, DuplicateJobTypeError } from './job-definition-registry';
import { REVIEW_CARD_GENERATION_JOB_DEFINITION } from './review-card-generation-job-definition';

/**
 * M-AI-06-03: ReviewCard Generation Job Definition 注册服务
 *
 * 在模块初始化（onModuleInit）时向 JobDefinitionRegistry 注册
 * ReviewCard Generation JobDefinition。
 *
 * 容忍重复注册：API 进程和 Worker 进程各自独立启动，均导入
 * AiJobModule，因此同一 Definition 会被注册两次。第二次注册的
 * DuplicateJobTypeError 被安全捕获，不阻止进程启动。
 */
@Injectable()
export class ReviewCardGenerationRegistrationService implements OnModuleInit {
  private readonly logger = new Logger(ReviewCardGenerationRegistrationService.name);

  constructor(private readonly registry: JobDefinitionRegistry) {}

  onModuleInit(): void {
    try {
      this.registry.register(REVIEW_CARD_GENERATION_JOB_DEFINITION);
      this.logger.log(
        `ReviewCard Generation Job Definition registered: ` +
        `jobType="${REVIEW_CARD_GENERATION_JOB_DEFINITION.jobType}" ` +
        `queue="${REVIEW_CARD_GENERATION_JOB_DEFINITION.queue.queueName}" ` +
        `timeout=${REVIEW_CARD_GENERATION_JOB_DEFINITION.execution.timeoutMs}ms ` +
        `retries=${REVIEW_CARD_GENERATION_JOB_DEFINITION.execution.maxRetries}`,
      );
    } catch (err: unknown) {
      if (err instanceof DuplicateJobTypeError) {
        this.logger.log(
          `ReviewCard Generation Job Definition already registered ` +
          `(by another process — e.g. API + Worker both import AiJobModule)`,
        );
      } else {
        throw err;
      }
    }
  }
}
