// Writes the database, its archive and the stored files for the server (MySQL 8):  npm run export:server -- <folder>
// Reads only. Demo accounts, sign-in sessions, backup history and waiting emails are left out.
import "dotenv/config";
import { spawn } from "node:child_process";
import { cpSync, createWriteStream, existsSync, mkdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { env } from "../src/config/env.js";

const out = resolve(process.argv[2] ?? "for_server"), u = new URL(process.env["EXPORT_DATABASE_URL"] ?? process.env["BACKUP_DATABASE_URL"] ?? env.DATABASE_URL), db = u.pathname.slice(1), archive = env.ARCHIVE_DB ?? `${db}_v1_archive`;
mkdirSync(out, { recursive: true });
const bin = env.MYSQL_BIN_DIR ? join(env.MYSQL_BIN_DIR, process.platform === "win32" ? "mysqldump.exe" : "mysqldump") : "mysqldump";
const base = [`--host=${u.hostname}`, `--port=${u.port || 3306}`, `--user=${decodeURIComponent(u.username)}`, "--single-transaction", "--skip-lock-tables", "--hex-blob", "--default-character-set=utf8mb4", "--skip-comments", "--no-tablespaces", "--net-buffer-length=400K"];
const DEMO = "%@demo.pbps.invalid", EMPTY = ["user_sessions", "idempotency_keys", "scheduler_leases", "email_otp_challenges", "user_tokens", "backup_runs"];
/** MariaDB writes a few things MySQL 8 does not read. */
const clean = (l: string) => l.replace(/^\/\*M?!999999.*$/, "").replace(/\bcurrent_timestamp\((\d)\)/g, "CURRENT_TIMESTAMP($1)").replace(/ DEFAULT current_timestamp\(\)/g, " DEFAULT CURRENT_TIMESTAMP").replace(/ON UPDATE current_timestamp\(\)/g, "ON UPDATE CURRENT_TIMESTAMP").replace(/ PAGE_CHECKSUM=\d/g, "").replace(/ TRANSACTIONAL=\d/g, "");
async function dump(name: string, file: string, calls: string[][], tail = ""): Promise<void> {
  const w = createWriteStream(join(out, file), "utf8"), write = (s: string) => (w.write(s) ? Promise.resolve() : new Promise<void>((r) => w.once("drain", () => r())));
  await write("SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\nSET UNIQUE_CHECKS=0;\nSET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';\n");
  // mysqldump of MariaDB also writes the values of generated columns, which MySQL 8 refuses: they load as plain columns and become generated at the end.
  let table = ""; const generated: string[] = [];
  for (const extra of calls) {
    const p = spawn(bin, [...base, ...extra.filter((x) => x.startsWith("--")), name, ...extra.filter((x) => !x.startsWith("--"))], { env: { ...process.env, MYSQL_PWD: decodeURIComponent(u.password) } });
    let err = ""; p.stderr.on("data", (b: Buffer) => { err += b.toString(); });
    const done = new Promise<number>((r) => p.on("close", (c) => r(c ?? 1)));
    for await (const line of createInterface({ input: p.stdout, crlfDelay: Infinity })) {
      table = /^CREATE TABLE `(\w+)`/.exec(line)?.[1] ?? table;
      const g = /^ {2}(`\w+` .*?) GENERATED ALWAYS AS (\(.+\) STORED.*?),?$/.exec(line);
      if (g) generated.push(`ALTER TABLE \`${table}\` MODIFY ${g[1]} GENERATED ALWAYS AS ${g[2]};\n`);
      await write(`${clean(g ? line.replace(/ GENERATED ALWAYS AS \(.+\) STORED/, "") : line)}\n`);
    }
    if (await done) throw new Error(`${name}: ${err.trim().slice(0, 400)}`);
  }
  await write(`${generated.join("")}${tail}SET FOREIGN_KEY_CHECKS=1;\nSET UNIQUE_CHECKS=1;\n`);
  await new Promise<void>((r) => w.end(() => r()));
  console.log(`${file} written from ${name}`);
}
const demo = `(SELECT id FROM (SELECT id FROM users WHERE email LIKE '${DEMO}') x)`;
await dump(db, "pbps_v2.sql", [[]], `${EMPTY.map((t) => `DELETE FROM ${t};\n`).join("")}DELETE FROM email_outbox WHERE status IN ('queued','sending');
DELETE FROM membership_scopes WHERE membership_id IN (SELECT id FROM memberships WHERE user_id IN ${demo});
DELETE FROM notifications WHERE user_id IN ${demo};
DELETE FROM memberships WHERE user_id IN ${demo};
UPDATE users SET status='disabled' WHERE email LIKE '${DEMO}';
`);
await dump(archive, "pbps_v2_v1_archive.sql", [[]]);
if (existsSync(env.STORAGE_DIR)) { cpSync(env.STORAGE_DIR, join(out, "storage"), { recursive: true }); console.log("storage copied"); }
console.log(`\nReady in ${out}. Import as described in docs/05_DEPLOYMENT.md.`);
