// src/lib/backlink/queries.test.ts — integration, gated on DB_TESTS=1.
import { beforeEach, describe, expect, mock, test } from "bun:test";

// server-only throws outside Next.js; stub it for the test runner.
mock.module("server-only", () => ({}));

const RUN_DB = process.env.DB_TESTS === "1";

describe.skipIf(!RUN_DB)("getReservoir DR resolution (postgres)", () => {
  let db: typeof import("@/lib/db/client").db;
  let linkSources: typeof import("@/lib/db/domain-schema").linkSources;
  let domainRatings: typeof import("@/lib/db/domain-schema").domainRatings;
  let getReservoir: typeof import("./queries").getReservoir;
  const ORG = "demo-org"; // guaranteed by db:seed / test DB setup

  beforeEach(async () => {
    ({ db } = await import("@/lib/db/client"));
    const schema = await import("@/lib/db/domain-schema");
    linkSources = schema.linkSources;
    domainRatings = schema.domainRatings;
    ({ getReservoir } = await import("./queries"));
    const { assertTestDb } = await import("@/lib/db/assert-test-db");
    await assertTestDb();
    await db.delete(linkSources);
    await db.delete(domainRatings);
  });

  test("getReservoir resolves dr from the shared cache by domainNorm", async () => {
    await db.insert(linkSources).values({
      id: "ls1",
      orgId: ORG,
      platform: "PH",
      url: "https://producthunt.com",
      domainNorm: "producthunt.com",
      kind: "launch-platform",
      da: 40,
      effort: "low",
      linkType: "dofollow",
      language: "en",
    } as never);
    await db
      .insert(domainRatings)
      .values({ domainNorm: "producthunt.com", dr: 91 });

    const { sources } = await getReservoir(ORG);
    const s = sources.find((x) => x.id === "ls1")!;
    expect(s.dr).toBe(91); // cache wins
    expect(s.da).toBe(40); // manual kept as fallback data
  });

  test("dr is null when no cache row exists", async () => {
    await db.insert(linkSources).values({
      id: "ls2",
      orgId: ORG,
      platform: "X",
      url: "https://x.io",
      domainNorm: "x.io",
      kind: "other",
      da: null,
      effort: "low",
      linkType: "dofollow",
      language: "en",
    } as never);
    const { sources } = await getReservoir(ORG);
    expect(sources.find((x) => x.id === "ls2")!.dr).toBeNull();
  });
});
