import type { SessionConfirmJobData } from "@/modules/address/session-confirm-queue-types";
import { saveSessionConfirmResult } from "@/modules/address/session-confirm-queue";
import { RpaError } from "@/modules/rpa/errors";
import { confirmAddressesOnParkedSession } from "@/workers/rpa/session-address-confirm";
import { withRpaSessionLock } from "@/workers/rpa/session-manager";

export async function processSessionConfirmJob(
  data: SessionConfirmJobData,
): Promise<void> {
  try {
    await withRpaSessionLock(async () => {
      await confirmAddressesOnParkedSession({
        sessionId: data.sessionId,
        pickup: data.pickup,
        delivery: data.delivery,
      });
    });
    await saveSessionConfirmResult(data.jobId, { ok: true });
  } catch (error) {
    if (error instanceof RpaError) {
      await saveSessionConfirmResult(data.jobId, {
        ok: false,
        code: error.code,
        message: error.message,
        retryable: error.retryable,
      });
      return;
    }
    await saveSessionConfirmResult(data.jobId, {
      ok: false,
      code: "PAGE_LOAD_TIMEOUT",
      message: error instanceof Error ? error.message : "地址确认失败",
      retryable: true,
    });
  }
}
