import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
import { migrate } from "drizzle-orm/postgres-js/migrator";

function loadEnv() {
  const loadEnvFile = process.loadEnvFile as ((path?: string) => void) | undefined;
  if (!loadEnvFile) return;

  for (const envPath of [resolve(process.cwd(), ".env"), resolve(process.cwd(), "../.env"), resolve(process.cwd(), "../../.env")]) {
    if (existsSync(envPath)) {
      loadEnvFile(envPath);
      return;
    }
  }
}

loadEnv();

async function main() {
  const { getDb, getSql } = await import("./client");
  const db = getDb();
  await migrate(db, { migrationsFolder: resolve(__dirname, "../drizzle") });

  // Drizzle applies every pending file in one transaction. Postgres will not
  // use a newly-added enum label until that ADD VALUE is committed, so the
  // live-Connect unique index lives here instead of in 0021.
  await getSql().unsafe(`
    CREATE UNIQUE INDEX IF NOT EXISTS "calls_live_connect_channel_idx"
      ON "calls" ("channel_id")
      WHERE "kind" = 'connect' AND "status" IN ('ringing', 'active') AND "channel_id" IS NOT NULL
  `);

  const rlsSql = readFileSync(resolve(__dirname, "../sql/rls.sql"), "utf8");
  await getSql().unsafe(rlsSql);

  const searchSql = readFileSync(resolve(__dirname, "../sql/search.sql"), "utf8");
  await getSql().unsafe(searchSql);

  console.log("Migrations + RLS policies + search indexes applied.");
  await getSql().end();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
