// Puts a backup into a NEW, EMPTY database:  npm run backup:restore -- <backup folder> <new database>
// It never touches the database that is in use. Point DATABASE_URL at the new database afterwards.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { env } from "../src/config/env.js";
import { pool } from "../src/core/db/db.js";
import { counts, load, sha256File } from "../src/modules/backups/dump.js";

const [folder, target] = process.argv.slice(2);
if (!folder || !target || !/^\w{1,64}$/.test(target)) throw new Error("Usage: npm run backup:restore -- <backup folder> <new database>");
if (target === new URL(env.DATABASE_URL).pathname.slice(1)) throw new Error("Choose a new database, not the one in use.");
if (Object.keys(await counts(target)).length) throw new Error(`${target} is not empty. Create a new, empty database.`);
const m = JSON.parse(readFileSync(join(folder, "manifest.json"), "utf8")) as { databases: { database: string; file: string; sha256: string; rows: Record<string, number> }[] };
const part = process.argv[4] === "--archive" ? m.databases[1] : m.databases[0];
if (!part) throw new Error("This backup does not hold that database.");
if ((await sha256File(join(folder, part.file))) !== part.sha256) throw new Error("The backup file has changed since it was made. Nothing was restored.");
await load(join(folder, part.file), target);
const now = await counts(target), bad = Object.entries(part.rows).filter(([t, n]) => now[t] !== n);
if (bad.length) throw new Error(`These tables are not complete: ${bad.map(([t]) => t).join(", ")}`);
console.log(`Restored ${Object.keys(now).length} tables and ${Object.values(now).reduce((a, b) => a + b, 0)} rows into ${target}. Every table was counted.`);
await pool.end();
