import { DatabaseSync, backup } from "node:sqlite";
import {
  existsSync,
  mkdirSync,
  chmodSync,
  readFileSync,
  writeFileSync,
} from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
const source = path.resolve(process.env.DB_PATH || "data/stockroom.sqlite");
if (!existsSync(source))
  throw new Error("Database does not exist. No backup created.");
const directory = path.resolve(process.argv[2] || "data/backups");
mkdirSync(directory, { recursive: true, mode: 0o700 });
const target = path.join(
  directory,
  `stockroom-${new Date().toISOString().replaceAll(":", "-")}.sqlite`,
);
const db = new DatabaseSync(source, { readOnly: true });
await backup(db, target);
db.close();
chmodSync(target, 0o600);
const restored = new DatabaseSync(target, { readOnly: true });
if (restored.prepare("PRAGMA integrity_check").get().integrity_check !== "ok")
  throw new Error("Backup integrity check failed.");
const summary = Object.fromEntries(
  ["tenants", "products", "lots", "movements"].map((t) => [
    t,
    restored.prepare(`SELECT COUNT(*) n FROM ${t}`).get().n,
  ]),
);
restored.close();
writeFileSync(
  target + ".sha256",
  crypto.createHash("sha256").update(readFileSync(target)).digest("hex") + "\n",
  { mode: 0o600 },
);
console.log(
  JSON.stringify({ backup: target, verified: true, records: summary }),
);
