"use strict";

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

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

  const migrateDisabled = String(process.env.DB_MIGRATE_DISABLE || "")
    .trim()
    .toLowerCase();
  if (migrateDisabled === "1" || migrateDisabled === "true" || migrateDisabled === "yes") {
    console.log("DB migrations are disabled by DB_MIGRATE_DISABLE. Skipping.");
    return;
  }

  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.log("No pending migrations.");
    return;
  }

  for (const file of pending) {
    console.log(`Applying: ${file}`);
    applyMigration(databaseUrl, file);
  }

  console.log(`Applied ${pending.length} migration(s).`);
}

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