import { Injectable, OnModuleInit } from '@nestjs/common';
import { BackgroundJobWorker } from '../jobs/background-job.worker';
import { XIAOBAO_SUMMARY_REFRESH_JOB } from './xiaobao-risk.types';
import { XiaobaoRiskService } from './xiaobao-risk.service';

@Injectable()
export class XiaobaoRiskWorker implements OnModuleInit {
  constructor(
    private readonly worker: BackgroundJobWorker,
    private readonly risks: XiaobaoRiskService,
  ) {}

  onModuleInit() {
    this.worker.registerHandler(XIAOBAO_SUMMARY_REFRESH_JOB, async (payload) => {
      const versionId = readVersionId(payload);
      if (!versionId) throw new Error('xiaobao.summary.refresh requires payload.versionId');
      await this.risks.refreshSummary(versionId);
    });
  }
}

function readVersionId(payload: unknown): string | undefined {
  if (!payload || typeof payload !== 'object') return undefined;
  const value = (payload as { versionId?: unknown }).versionId;
  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
