import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { env } from "../../config/env.js";
import { audit } from "../../core/audit/audit.js";
import { execute, insert, one, pool, query } from "../../core/db/db.js";
import { defineJob, enqueue, projectIds } from "../../core/jobs/jobs.js";
import { conflict, type Ctx } from "../../core/http/route.js";
import { notifyRoles } from "../notifications/index.js";
import { copyTree, counts, dump, restoreCheck, sha256File } from "./dump.js";
import { expired } from "./retention.rules.js";

const ready = () => Boolean(env.BACKUP_DATABASE_URL && env.BACKUP_DIR);
const databases = () => { const main = new URL(env.DATABASE_URL).pathname.slice(1); return [main, env.ARCHIVE_DB ?? `${main}_v1_archive`]; };
const exists = async (name: string) => Boolean(await one(pool, "SELECT 1 AS x FROM information_schema.schemata WHERE schema_name=?", [name]));

export async function list() {
  const rows = await query(pool, "SELECT b.*, u.name AS who FROM backup_runs b LEFT JOIN users u ON u.id=b.requested_by ORDER BY b.id DESC LIMIT 30");
  const last = await one(pool, "SELECT finished_at AS t FROM backup_runs WHERE status='ok' ORDER BY id DESC LIMIT 1");
  return { configured: ready(), hour: env.BACKUP_HOUR, folder: env.BACKUP_DIR ?? "", secondCopy: Boolean(env.BACKUP_COPY_DIR), lastGood: last?.["t"] ?? null,
    runs: rows.map((b) => ({ id: b["id"], kind: b["kind"], status: b["status"], startedAt: b["started_at"], finishedAt: b["finished_at"], sizeMb: b["size_bytes"] === null ? null : Math.round(b["size_bytes"] / 104_857.6) / 10, tables: b["tables_checked"], rows: b["rows_checked"], files: b["files_copied"], error: b["error"], requestedBy: b["who"] ?? "Automatic" })) };
}
export async function start(c: Ctx) {
  if (!ready()) conflict("BACKUP_NOT_SET_UP", "Backups are not set up on this server yet.");
  const jobId = await enqueue(pool, "backup.run", { kind: "manual", by: c.user.id }, { projectId: c.pid, userId: c.user.id, dedupe: "backup:manual" });
  await audit(pool, c, { module: "backups", action: "requested", entityType: "backup", entityId: jobId, summary: "Backup requested" });
  return { jobId };
}
/** Once a day after BACKUP_HOUR (Addis Ababa time). If the server was off at that hour, the backup runs as soon as it is on again. */
export async function scheduleBackup(now = Date.now()): Promise<void> {
  const local = new Date(now + 3 * 3_600_000);
  if (!ready() || local.getUTCHours() < env.BACKUP_HOUR) return;
  const day = local.toISOString().slice(0, 10);
  const done = await one(pool, "SELECT 1 AS x FROM backup_runs WHERE kind='nightly' AND (status='ok' OR started_at>UTC_TIMESTAMP(3)-INTERVAL 1 HOUR) AND DATE(started_at+INTERVAL 3 HOUR)=?", [day]);
  if (!done) await enqueue(pool, "backup.run", { kind: "nightly" }, { dedupe: `backup:${day}` });
}
/** Every table of both databases is dumped, restored into a throwaway database, and counted. Only then is the backup called good. */
async function run(kind: string, by: string | null, note: (pct: number, text: string) => Promise<void>) {
  const id = await insert(pool, "backup_runs", { kind, requested_by: by });
  const name = new Date(Date.now() + 3 * 3_600_000).toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-"), dir = join(env.BACKUP_DIR!, name);
  const beat = setInterval(() => void note(50, "Working").catch(() => undefined), 60_000);
  try {
    await mkdir(dir, { recursive: true });
    const manifest: Record<string, unknown>[] = [];
    let size = 0, tables = 0, rows = 0;
    for (const db of databases()) {
      if (!(await exists(db))) continue;
      await note(10, `Saving ${db}`);
      const file = join(dir, `${db}.sql.gz`), before = await counts(db);
      await dump(db, file);
      const after = await counts(db);
      await note(50, `Testing the copy of ${db}`);
      const restored = await restoreCheck(db, file);
      for (const t of Object.keys(before)) {
        const n = restored[t] ?? -1, lo = Math.min(before[t]!, after[t] ?? 0), hi = Math.max(before[t]!, after[t] ?? 0);
        if (n < lo || n > hi) throw new Error(`The copy of ${db}.${t} has ${n} rows, the database has ${before[t]}.`);
        tables++; rows += n;
      }
      const bytes = (await stat(file)).size;
      size += bytes;
      manifest.push({ database: db, file: `${db}.sql.gz`, bytes, sha256: await sha256File(file), rows: restored });
    }
    await note(80, "Saving uploaded files");
    const files = await copyTree(env.STORAGE_DIR, join(env.BACKUP_DIR!, "files"));
    await writeFile(join(dir, "manifest.json"), JSON.stringify({ madeAt: new Date().toISOString(), kind, databases: manifest }, null, 1));
    if (env.BACKUP_COPY_DIR) { await copyTree(dir, join(env.BACKUP_COPY_DIR, name)); await copyTree(join(env.BACKUP_DIR!, "files"), join(env.BACKUP_COPY_DIR, "files")); }
    await execute(pool, "UPDATE backup_runs SET status='ok', folder=?, size_bytes=?, tables_checked=?, rows_checked=?, files_copied=?, finished_at=UTC_TIMESTAMP(3) WHERE id=?", [dir.slice(0, 255), size, tables, rows, files, id]);
    const kept = await readdir(env.BACKUP_DIR!), folders = new Set((await query(pool, "SELECT folder FROM backup_runs WHERE status='ok'")).map((x) => String(x["folder"])));
    for (const old of expired(kept, name)) if (folders.has(join(env.BACKUP_DIR!, old).slice(0, 255))) await rm(join(env.BACKUP_DIR!, old), { recursive: true });
    return { message: `Backup saved and tested: ${tables} tables, ${rows} rows.` };
  } catch (error) {
    const text = String((error as Error).message).slice(0, 850);
    await execute(pool, "UPDATE backup_runs SET status='failed', error=?, finished_at=UTC_TIMESTAMP(3) WHERE id=?", [text, id]);
    await rm(dir, { recursive: true, force: true });
    for (const p of await projectIds()) await notifyRoles(pool, p, { roles: ["system_admin"], type: "backup.failed", severity: "critical", title: "The database backup failed", body: text.slice(0, 400), link: `/p/${p}/admin/backups`, dedupe: `backup-failed:${name.slice(0, 10)}`, email: true });
    throw error;
  } finally { clearInterval(beat); }
}
defineJob("backup.run", (job) => run(String(job.payload["kind"] ?? "manual"), job.userId, job.progress));
