// src/lib/db/db.test.ts
// Integration test — requires a running Postgres + the test DB migrated.
// Skipped unless DB_TESTS=1 (so the pure `bun test` stays PG-free).
// Run with: bun run test:db
import { afterAll, beforeAll, describe, expect, test } from "bun:test";

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

describe.skipIf(!RUN_DB)("db integration (postgres)", () => {
  let mod: typeof import("./client");
  let schema: typeof import("./schema");

  beforeAll(async () => {
    mod = await import("./client");
    schema = await import("./schema");
    // Hard guard: never delete against a non-*_test DB.
    const { assertTestDb } = await import("./assert-test-db");
    await assertTestDb();
    await mod.db.delete(schema.healthCheck); // clean slate
  });

  afterAll(async () => {
    // Don't close the shared singleton client here: bun runs every *.test.ts in
    // this directory in ONE process, so ending the pool hands the next file
    // (partitioning.test.ts) a CONNECTION_ENDED. The runtime tears the
    // connection down on process exit anyway; just clean the table we touched.
    await mod.db.delete(schema.healthCheck);
  });

  test("inserts and reads back a row through Drizzle", async () => {
    await mod.db.insert(schema.healthCheck).values({ note: "ping" });
    const rows = await mod.db.select().from(schema.healthCheck);
    expect(rows).toHaveLength(1);
    expect(rows[0].note).toBe("ping");
    expect(rows[0].checkedAt).toBeInstanceOf(Date);
  });
});
