"use strict";

const fs = require("fs");
const path = require("path");
const { migrationsDir } = require("./db-migrate-common");

function sanitizeName(input) {
  return String(input || "")
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "");
}

function timestampUtc() {
  const now = new Date();
  const pad = (value) => String(value).padStart(2, "0");
  return [
    now.getUTCFullYear(),
    pad(now.getUTCMonth() + 1),
    pad(now.getUTCDate()),
    "_",
    pad(now.getUTCHours()),
    pad(now.getUTCMinutes()),
    pad(now.getUTCSeconds()),
  ].join("");
}

function main() {
  const rawName = process.argv.slice(2).join(" ").trim();
  if (!rawName || process.argv.includes("--help")) {
    console.log("Usage: npm run db:migrate:new -- <migration-name>");
    process.exit(rawName ? 0 : 1);
  }

  const name = sanitizeName(rawName);
  if (!name) {
    throw new Error("Migration name must contain letters or numbers.");
  }

  if (!fs.existsSync(migrationsDir)) {
    throw new Error(`Migrations directory not found: ${migrationsDir}`);
  }

  const filename = `${timestampUtc()}_${name}.sql`;
  const fullPath = path.join(migrationsDir, filename);
  if (fs.existsSync(fullPath)) {
    throw new Error(`Migration already exists: ${filename}`);
  }

  const template = [
    "BEGIN;",
    "",
    "-- Add schema changes here.",
    "",
    "COMMIT;",
    "",
  ].join("\n");

  fs.writeFileSync(fullPath, template, "utf8");
  console.log(`Created migration: ${path.relative(process.cwd(), fullPath)}`);
}

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