"use strict";

const {
  ensureDatabaseUrl,
  ensurePsql,
  ensureSchemaMigrationsTable,
  getAppliedMigrations,
  getMigrationFiles,
} = require("./db-migrate-common");

function main() {
  if (process.argv.includes("--help")) {
    console.log("Usage: npm run db:migrate:verify");
    process.exit(0);
  }

  const databaseUrl = ensureDatabaseUrl();
  ensurePsql();
  ensureSchemaMigrationsTable(databaseUrl);

  const files = getMigrationFiles();
  const applied = getAppliedMigrations(databaseUrl);
  const pending = files.filter((file) => !applied.has(file));

  if (pending.length > 0) {
    console.error("Pending migrations detected:");
    for (const file of pending) {
      console.error(`- ${file}`);
    }
    process.exit(1);
  }

  console.log("Migration verification passed. No pending migrations.");
}

try {
  main();
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
