import { getQuoteRpaQueue } from "@/workers/rpa/queue";

/** Worker 重启后清理 orphan active job，避免阻塞后续候选/询价 */
export async function recoverOrphanActiveJobs(): Promise<number> {
  const queue = getQuoteRpaQueue();
  const active = await queue.getJobs(["active"], 0, 30);
  let recovered = 0;
  for (const job of active) {
    try {
      await job.moveToFailed(
        new Error("worker restart orphan recovery"),
        "0",
        true,
      );
      recovered += 1;
      console.warn(
        `[rpa-queue] 已回收 orphan active job name=${job.name} id=${job.id}`,
      );
    } catch {
      /* 可能已被其他 worker 接管 */
    }
  }
  return recovered;
}
