// src/lib/db/constraints.test.ts — DB-level invariants added by the sec audit
// (S2: CHECK constraints on 0-100 score columns). Integration test — requires
// a running Postgres + the test DB migrated. Skipped unless DB_TESTS=1.
// Run with: bun run test:db
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { eq } from "drizzle-orm";

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

describe.skipIf(!RUN_DB)("CHECK constraints (postgres)", () => {
  let db: typeof import("./client").db;
  let schema: typeof import("./domain-schema");

  beforeAll(async () => {
    ({ db } = await import("./client"));
    schema = await import("./domain-schema");
    const { assertTestDb } = await import("./assert-test-db");
    await assertTestDb();
    await db
      .delete(schema.domainRatings)
      .where(eq(schema.domainRatings.domainNorm, "check-test.example"));
  });

  afterAll(async () => {
    await db
      .delete(schema.domainRatings)
      .where(eq(schema.domainRatings.domainNorm, "check-test.example"));
  });

  // domain_ratings has no FK dependencies, making it the simplest table to
  // exercise the `domain_ratings_dr_range` CHECK directly. Drizzle's insert
  // builder is a thenable, not a native Promise — bun's `.rejects` matcher
  // needs a real Promise to await, so wrap the call in an async closure.
  test("rejects a dr value above 100", async () => {
    await expect(
      (async () => {
        await db.insert(schema.domainRatings).values({
          domainNorm: "check-test.example",
          dr: 150,
        });
      })(),
    ).rejects.toThrow();
  });

  test("rejects a negative dr value", async () => {
    await expect(
      (async () => {
        await db.insert(schema.domainRatings).values({
          domainNorm: "check-test.example",
          dr: -5,
        });
      })(),
    ).rejects.toThrow();
  });

  test("accepts a dr value within 0-100", async () => {
    await db.insert(schema.domainRatings).values({
      domainNorm: "check-test.example",
      dr: 42,
    });
    const [row] = await db
      .select()
      .from(schema.domainRatings)
      .where(eq(schema.domainRatings.domainNorm, "check-test.example"));
    expect(row.dr).toBe(42);
  });
});
