import { NextResponse } from "next/server"; import { randomBytes } from "crypto"; import { unlink } from "fs/promises"; import { tmpdir } from "os"; import { join } from "path"; import { getDb } from "@/lib/db"; /** * Lädt einen konsistenten SQLite-Snapshot herunter (VACUUM INTO läuft * transaktional, auch bei parallelen Schreibzugriffen). Enthält Gutscheine, * Kontakte, Mitglieder, Regeln, Logs und verschlüsselte Einstellungen. * Wiederherstellen: Datei als /data/gutscheine.db ablegen (gleicher * SETTINGS_ENCRYPTION_KEY erforderlich). */ export async function GET() { const db = getDb(); const stamp = new Date().toISOString().slice(0, 16).replace(/[-:T]/g, ""); const tmpPath = join(tmpdir(), `gutscheintracker-backup-${stamp}-${randomBytes(4).toString("hex")}.db`); try { await db.$executeRawUnsafe(`VACUUM INTO '${tmpPath.replace(/'/g, "''")}'`); const { readFile } = await import("fs/promises"); const data = await readFile(tmpPath); await unlink(tmpPath).catch(() => {}); return new NextResponse(new Uint8Array(data), { headers: { "content-type": "application/x-sqlite3", "content-disposition": `attachment; filename="gutscheintracker-backup-${stamp}.db"`, }, }); } catch (e) { await unlink(tmpPath).catch(() => {}); return NextResponse.json( { error: e instanceof Error ? e.message : "Backup fehlgeschlagen" }, { status: 500 } ); } }