"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:status");
    process.exit(0);
  }

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

  const files = getMigrationFiles();
  const applied = getAppliedMigrations(databaseUrl);

  let pendingCount = 0;
  for (const file of files) {
    const status = applied.has(file) ? "APPLIED" : "PENDING";
    if (status === "PENDING") pendingCount += 1;
    console.log(`${status}  ${file}`);
  }

  console.log("");
  console.log(`Total: ${files.length}`);
  console.log(`Applied: ${files.length - pendingCount}`);
  console.log(`Pending: ${pendingCount}`);
}

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