import { saveAddressCandidatesResult } from "@/modules/address/candidates-queue";
import type { AddressCandidatesJobData } from "@/modules/address/candidates-queue-types";
import { RpaError } from "@/modules/rpa/errors";
import { fetchMothershipAddressCandidates } from "@/workers/rpa/address-candidates";

/** 地址候选 job：与询价共用 worker 进程与 session-manager */
export async function processAddressCandidatesJob(
  data: AddressCandidatesJobData,
): Promise<void> {
  try {
    const result = await fetchMothershipAddressCandidates({
      pickup: data.pickup,
      delivery: data.delivery,
    });
    await saveAddressCandidatesResult(data.jobId, { ok: true, data: result });
  } catch (error) {
    if (error instanceof RpaError) {
      await saveAddressCandidatesResult(data.jobId, {
        ok: false,
        code: error.code,
        message: error.message,
        retryable: error.retryable,
      });
      return;
    }
    await saveAddressCandidatesResult(data.jobId, {
      ok: false,
      code: "PAGE_LOAD_TIMEOUT",
      message: error instanceof Error ? error.message : "地址候选 RPA 失败",
      retryable: true,
    });
  }
}
