import { readFileSync, readdirSync } from "fs";
import path from "path";

/**
 * Global integration setup.
 *
 * Only needed when running against a real Postgres via TEST_DATABASE_URL: reset the
 * schema and apply every Drizzle migration once before the workers start. When
 * TEST_DATABASE_URL is not set, each worker spins up its own in-process PGlite
 * database (see tests/helpers/integration-setup.ts) and this is a no-op.
 */

const MIGRATIONS_DIR = path.resolve(process.cwd(), "lib", "db", "migrations");

export default async function setup() {
  const connectionString = process.env.TEST_DATABASE_URL?.trim();
  if (!connectionString) {
    return;
  }

  const pg = (await import("pg")).default;
  const client = new pg.Client({ connectionString });
  await client.connect();
  try {
    await client.query("DROP SCHEMA IF EXISTS public CASCADE; CREATE SCHEMA public;");
    const files = readdirSync(MIGRATIONS_DIR)
      .filter((entry) => entry.endsWith(".sql"))
      .sort();
    for (const file of files) {
      await client.query(readFileSync(path.join(MIGRATIONS_DIR, file), "utf8"));
    }
  } finally {
    await client.end();
  }
}
