import { collectJobDedupKeys } from "@shared/job-fingerprint";
import type { JobListItem, JobStatus } from "@shared/types";

export type DuplicateDismissReason = "skipped" | "applied";

/**
 * Map open jobs to a prior skip/apply when employer+title or description matches.
 */
export function buildDuplicateDismissHints(
  jobs: readonly JobListItem[],
): Map<string, DuplicateDismissReason> {
  const dismissedKeys = new Map<string, DuplicateDismissReason>();

  for (const job of jobs) {
    if (job.status !== "skipped" && job.status !== "applied") continue;
    const reason: DuplicateDismissReason =
      job.status === "applied" ? "applied" : "skipped";
    for (const key of collectJobDedupKeys({
      employer: job.employer,
      title: job.title,
    })) {
      if (!dismissedKeys.has(key)) dismissedKeys.set(key, reason);
    }
  }

  const hints = new Map<string, DuplicateDismissReason>();
  const openStatuses = new Set<JobStatus>([
    "discovered",
    "ready",
    "processing",
  ]);

  for (const job of jobs) {
    if (!openStatuses.has(job.status)) continue;
    for (const key of collectJobDedupKeys({
      employer: job.employer,
      title: job.title,
    })) {
      const reason = dismissedKeys.get(key);
      if (reason) {
        hints.set(job.id, reason);
        break;
      }
    }
  }

  return hints;
}

export { collectJobDedupKeys };
