import { Logger } from '@nestjs/common';
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { QueueName } from '../queue-names';
import type { ExecutionCallbackJob } from '../job-payloads';
import { ExecutionCallbackService } from '../../modules/plan/execution-callback.service';

/**
 * execution-callback worker — 把客服执行结果 POST 回宿主 callbackUrl(HMAC 签名)。
 *
 * 触发:ExecutionService.submit 提交成功且宿主配了 callbackUrl → 入队。
 * 重试:非 2xx / 超时 → 抛错交 BullMQ 退避(QueueDefaults);耗尽入 failed 集(死信,Bull Board 可见)。
 * 幂等:jobId = executionId,同一 execution 不重复入队;宿主侧再按 X-PAC-Event-Id 去重(at-least-once)。
 */
@Processor(QueueName.EXECUTION_CALLBACK, { concurrency: 4 })
export class ExecutionCallbackProcessor extends WorkerHost {
  private readonly logger = new Logger(ExecutionCallbackProcessor.name);

  constructor(private readonly callback: ExecutionCallbackService) {
    super();
  }

  async process(job: Job<ExecutionCallbackJob>): Promise<{ delivered: boolean; skipped?: string }> {
    const { executionId } = job.data;
    const r = await this.callback.deliver(executionId);
    if (r.skipped) {
      this.logger.debug(`execution-callback skip execution=${executionId.slice(0, 8)}: ${r.skipped}`);
    }
    return { delivered: r.delivered, skipped: r.skipped };
  }
}
