/**
 * Apply pending migrations. Safe to run repeatedly; Drizzle tracks what has
 * already been applied.
 */
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const url = process.env.DATABASE_URL;
if (!url) {
  console.error('DATABASE_URL is not set.');
  process.exit(1);
}

const migrationsFolder = join(dirname(fileURLToPath(import.meta.url)), '..', 'migrations');

// max: 1 — migrations must run on a single connection, in order.
const sql = postgres(url, { max: 1 });
try {
  await migrate(drizzle(sql), { migrationsFolder });
  console.log('Migrations applied.');
} finally {
  await sql.end();
}
