#!/usr/bin/env node
/**
 * Post-migration verification.
 * Called by .gitea/workflows/deploy.yml after npm run migrate:one.
 * Confirms critical table admin_users is queryable.
 */
const { Client } = require("pg");

async function main() {
  const url = process.env.DATABASE_URL;
  if (!url) {
    console.error("No DATABASE_URL");
    process.exit(1);
  }

  const c = new Client({ connectionString: url });
  await c.connect();

  try {
    console.log("=== Post-migration verification: critical table admin_users must exist ===");
    await c.query("SELECT 1 FROM admin_users LIMIT 1");
    console.log("✓ admin_users table exists and is queryable");
    process.exit(0);
  } catch (e) {
    console.error("✗ FATAL: admin_users relation missing after migrate:", e.message);
    console.error("The deploy cannot continue. The secret DATABASE_URL must have had db/migrations/0001_init.sql applied successfully.");
    process.exit(1);
  } finally {
    await c.end();
  }
}

main();