import { PRIOR_SKIP_DISMISS_LOOKBACK_MS } from "@shared/job-fingerprint";
import { createJob } from "@shared/testing/factories";
import { describe, expect, it } from "vitest";
import { buildDuplicateDismissHints } from "./job-dedup";

describe("buildDuplicateDismissHints", () => {
  const now = Date.parse("2026-06-10T12:00:00.000Z");
  const recentUpdatedAt = new Date(
    now - PRIOR_SKIP_DISMISS_LOOKBACK_MS + 86_400_000,
  ).toISOString();
  const staleUpdatedAt = new Date(
    now - PRIOR_SKIP_DISMISS_LOOKBACK_MS - 86_400_000,
  ).toISOString();

  it("flags open jobs that match a skipped posting", () => {
    const jobs = [
      createJob({
        id: "skipped-1",
        employer: "Acme",
        title: "SDET",
        status: "skipped",
        updatedAt: recentUpdatedAt,
      }),
      createJob({
        id: "open-1",
        employer: "Acme Inc.",
        title: "SDET (Remote)",
        status: "discovered",
      }),
      createJob({
        id: "open-2",
        employer: "Contoso",
        title: "QA Engineer",
        status: "discovered",
      }),
    ];

    const hints = buildDuplicateDismissHints(jobs, now);
    expect(hints.get("open-1")).toBe("skipped");
    expect(hints.has("open-2")).toBe(false);
  });

  it("matches employer prefix and plural title variants", () => {
    const jobs = [
      createJob({
        id: "skipped-1",
        employer: "CGI",
        title: "Automation Test Engineer",
        status: "skipped",
        updatedAt: recentUpdatedAt,
      }),
      createJob({
        id: "open-1",
        employer: ". CGI IT UK Limited",
        title: "Automation Test Engineers",
        status: "discovered",
      }),
    ];

    const hints = buildDuplicateDismissHints(jobs, now);
    expect(hints.get("open-1")).toBe("skipped");
  });

  it("ignores skipped jobs older than the lookback window", () => {
    const jobs = [
      createJob({
        id: "skipped-1",
        employer: "Acme",
        title: "SDET",
        status: "skipped",
        updatedAt: staleUpdatedAt,
      }),
      createJob({
        id: "open-1",
        employer: "Acme",
        title: "SDET",
        status: "discovered",
      }),
    ];

    const hints = buildDuplicateDismissHints(jobs, now);
    expect(hints.has("open-1")).toBe(false);
  });

  it("does not match different titles at the same employer", () => {
    const jobs = [
      createJob({
        id: "skipped-1",
        employer: "Cognizant",
        title: "Automation Test Engineer",
        status: "skipped",
        updatedAt: recentUpdatedAt,
      }),
      createJob({
        id: "open-1",
        employer: "Cognizant",
        title: "AI Automation Test Engineer",
        status: "discovered",
      }),
    ];

    const hints = buildDuplicateDismissHints(jobs, now);
    expect(hints.has("open-1")).toBe(false);
  });
});
