import { describe, expect, it } from "vitest";
import {
  isLinkedInJobUrl,
  isPostingExpiredByDate,
  probeApplicationLink,
} from "../src/application-link.js";

describe("isLinkedInJobUrl", () => {
  it("matches LinkedIn job view URLs", () => {
    expect(
      isLinkedInJobUrl("https://www.linkedin.com/jobs/view/4362000000"),
    ).toBe(true);
  });

  it("rejects non-LinkedIn URLs", () => {
    expect(isLinkedInJobUrl("https://example.com/jobs/1")).toBe(false);
  });
});

describe("isPostingExpiredByDate", () => {
  it("returns true when expires_at is in the past", () => {
    expect(
      isPostingExpiredByDate(
        "2020-01-01T00:00:00.000Z",
        new Date("2025-01-01"),
      ),
    ).toBe(true);
  });

  it("returns false when expires_at is in the future", () => {
    expect(
      isPostingExpiredByDate(
        "2099-01-01T00:00:00.000Z",
        new Date("2025-01-01"),
      ),
    ).toBe(false);
  });
});

describe("probeApplicationLink", () => {
  it("marks expired when final URL is LinkedIn expired redirect", async () => {
    const fetchImpl = async () =>
      ({
        url: "https://www.linkedin.com/jobs/view/expired_jd_redirect/",
        status: 200,
        text: async () => "<html></html>",
      }) as Response;

    const result = await probeApplicationLink(
      "https://www.linkedin.com/jobs/view/123",
      fetchImpl,
    );
    expect(result?.expired).toBe(true);
  });

  it("extracts India location from HTML when not expired", async () => {
    const html = `
      <script type="application/ld+json">
      {"@type":"JobPosting","jobLocation":{"address":{"addressLocality":"Bengaluru","addressCountry":"India"}}}
      </script>`;
    const fetchImpl = async () =>
      ({
        url: "https://www.linkedin.com/jobs/view/123",
        status: 200,
        text: async () => html,
      }) as Response;

    const result = await probeApplicationLink(
      "https://www.linkedin.com/jobs/view/123",
      fetchImpl,
    );
    expect(result?.expired).toBe(false);
    expect(result?.location).toMatch(/India/i);
  });
});
