// src/lib/sites/assert-site.test.ts — integration, gated on DB_TESTS=1.
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { __clearTestCaller, __setTestCaller } from "./access";

// 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)("siteBelongsToOrg (postgres)", () => {
  let db: typeof import("@/lib/db/client").db;
  let schema: typeof import("@/lib/db/domain-schema");
  const ORG = "demo-org"; // guaranteed by db:seed / test DB setup
  const SITE = "wt-assert-site";

  beforeEach(async () => {
    __setTestCaller({ userId: "seed-owner", orgId: ORG, role: "owner" });
    ({ db } = await import("@/lib/db/client"));
    schema = await import("@/lib/db/domain-schema");
    const { assertTestDb } = await import("@/lib/db/assert-test-db");
    const { eq } = await import("drizzle-orm");
    await assertTestDb();
    await db.delete(schema.sites).where(eq(schema.sites.id, SITE));
    await db.insert(schema.sites).values({
      id: SITE,
      orgId: ORG,
      ownerUserId: "seed-owner",
      name: "WT Assert Site",
      url: "https://wt-assert-site.com",
      primaryLanguage: "fr",
      languages: [],
      targetCountries: ["FR"],
    });
  });

  afterEach(() => __clearTestCaller());

  test("vrai quand le site appartient à l'org", async () => {
    const { siteBelongsToOrg } = await import("./assert-site");
    expect(await siteBelongsToOrg(SITE, ORG)).toBe(true);
  });

  test("faux pour une autre org (tenancy)", async () => {
    const { siteBelongsToOrg } = await import("./assert-site");
    expect(await siteBelongsToOrg(SITE, "other-org")).toBe(false);
  });

  test("faux pour un site inexistant", async () => {
    const { siteBelongsToOrg } = await import("./assert-site");
    expect(await siteBelongsToOrg("ghost", ORG)).toBe(false);
  });
});
