import { Injectable, OnModuleInit } from '@nestjs/common';
import { BackgroundJobWorker } from '../jobs/background-job.worker';
import { XIAOBAO_AI_INTERPRET_JOB, XiaobaoAiInterpretPayload } from './xiaobao-ai.types';
import { XiaobaoAiService } from './xiaobao-ai.service';

@Injectable()
export class XiaobaoAiWorker implements OnModuleInit {
  constructor(
    private readonly worker: BackgroundJobWorker,
    private readonly xiaobaoAi: XiaobaoAiService,
  ) {}

  onModuleInit() {
    this.worker.registerHandler(XIAOBAO_AI_INTERPRET_JOB, async (payload) => {
      await this.xiaobaoAi.runInterpretation(readPayload(payload));
    });
  }
}

function readPayload(payload: unknown): XiaobaoAiInterpretPayload {
  if (!payload || typeof payload !== 'object') {
    throw new Error('xiaobao.ai.interpret requires payload.versionId and payload.riskSignature');
  }
  const versionId = (payload as { versionId?: unknown }).versionId;
  const riskSignature = (payload as { riskSignature?: unknown }).riskSignature;
  if (typeof versionId !== 'string' || !versionId.trim() || typeof riskSignature !== 'string' || !riskSignature.trim()) {
    throw new Error('xiaobao.ai.interpret requires payload.versionId and payload.riskSignature');
  }
  return { versionId: versionId.trim(), riskSignature: riskSignature.trim() };
}
