#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import "dotenv/config";

const args = process.argv.slice(2);

function getArg(name) {
  const index = args.indexOf(name);
  return index >= 0 ? args[index + 1] : undefined;
}

function hasFlag(name) {
  return args.includes(name);
}

function usage() {
  console.log(`Usage:
  node scripts/restore-plan.mjs --backup ./backups/qris.dump [--execute]

Default mode prints the restore command only. --execute runs pg_restore against the
configured PGDATABASE/DATABASE_URL target, so use it only on a prepared restore DB.
`);
}

if (hasFlag("--help") || hasFlag("-h")) {
  usage();
  process.exit(0);
}

const backup = getArg("--backup");
if (!backup) {
  usage();
  process.exit(1);
}

const backupPath = path.resolve(process.cwd(), backup);
if (!fs.existsSync(backupPath)) {
  throw new Error(`backup not found: ${backupPath}`);
}

const dbName = process.env.PGDATABASE || "qris_soundbox_platform";
const pgRestoreArgs = ["--clean", "--if-exists", "--no-owner"];
if (process.env.DATABASE_URL) {
  pgRestoreArgs.push("-d", process.env.DATABASE_URL);
} else {
  pgRestoreArgs.push("-h", process.env.PGHOST || "127.0.0.1");
  pgRestoreArgs.push("-p", String(process.env.PGPORT || 5432));
  pgRestoreArgs.push("-U", process.env.PGUSER || "postgres");
  pgRestoreArgs.push("-d", dbName);
}
pgRestoreArgs.push(backupPath);

const command = `pg_restore ${pgRestoreArgs.map((arg) => (arg.includes(" ") ? JSON.stringify(arg) : arg)).join(" ")}`;

if (!hasFlag("--execute")) {
  console.log(JSON.stringify({ execute: false, command, backup: backupPath }, null, 2));
  process.exit(0);
}

const result = spawnSync("pg_restore", pgRestoreArgs, {
  stdio: "inherit",
  env: process.env
});
if (result.status !== 0) {
  throw new Error(`pg_restore failed with status ${result.status}`);
}

console.log(JSON.stringify({ ok: true, backup: backupPath }, null, 2));
