#!/usr/bin/env node
/**
 * db:status — list applied migrations from the pg_migrations tracking table.
 * Usage: DATABASE_URL=... node scripts/db-status.mjs
 */

import pg from 'pg';
import process from 'node:process';

const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
  console.error('DATABASE_URL is required');
  process.exit(2);
}

const pool = new pg.Pool({ connectionString, max: 1 });
try {
  const result = await pool.query('SELECT id, name, run_on FROM pgmigrations ORDER BY id');
  if (result.rows.length === 0) {
    console.log('No migrations applied.');
  } else {
    for (const row of result.rows) {
      console.log(`${row.id}\t${row.name}\t(applied ${row.run_on})`);
    }
  }
} catch (error) {
  console.error('Failed to read migration status', error);
  process.exitCode = 1;
} finally {
  await pool.end();
}
