/**
 * Apply SQL migrations from ./drizzle (provider-portable boot step).
 * Usage: node --env-file=.env.production scripts/migrate.mjs
 *    or: DATABASE_URL=... node scripts/migrate.mjs
 */
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
import path from "node:path";
import { fileURLToPath } from "node:url";

const url = process.env.DATABASE_URL;
if (!url) {
  console.error("[migrate] DATABASE_URL is required");
  process.exit(1);
}

const here = path.dirname(fileURLToPath(import.meta.url));
const migrationsFolder = path.join(here, "..", "drizzle");

const sql = postgres(url, { max: 1 });
const db = drizzle(sql);

try {
  console.info("[migrate] applying migrations from", migrationsFolder);
  await migrate(db, { migrationsFolder });
  console.info("[migrate] done");
} catch (error) {
  console.error("[migrate] failed", error);
  process.exitCode = 1;
} finally {
  await sql.end({ timeout: 5 });
}
