import { expect, test } from "bun:test";
import { fetchDomainRating } from "./ahrefs-dr";

function mockFetch(status: number, body: unknown): typeof fetch {
  return (async () =>
    new Response(JSON.stringify(body), {
      status,
      headers: { "Content-Type": "application/json" },
    })) as unknown as typeof fetch;
}

test("parses and rounds a valid DR", async () => {
  const r = await fetchDomainRating(
    "producthunt.com",
    mockFetch(200, { domain_rating: { domain_rating: 72.6 } }),
  );
  expect(r).toEqual({ ok: true, dr: 73 });
});

test("429 → rate_limited", async () => {
  const r = await fetchDomainRating("x.com", mockFetch(429, {}));
  expect(r).toEqual({ ok: false, reason: "rate_limited" });
});

test("missing field → invalid; other non-2xx → error", async () => {
  expect(await fetchDomainRating("x.com", mockFetch(200, { nope: 1 }))).toEqual(
    {
      ok: false,
      reason: "invalid",
    },
  );
  expect(await fetchDomainRating("x.com", mockFetch(500, {}))).toEqual({
    ok: false,
    reason: "error",
  });
});
