import { error } from '@sveltejs/kit';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { BACKUP_DIR, safeName } from '$lib/server/backup.js';

export function GET({ params }) {
  const { name } = params;
  if (!safeName(name)) throw error(400, 'Invalid backup name');

  const path = join(BACKUP_DIR, name);
  if (!existsSync(path)) throw error(404, 'Backup not found');

  const buf = readFileSync(path);
  const size = statSync(path).size;

  return new Response(buf, {
    headers: {
      'Content-Type': 'application/octet-stream',
      'Content-Length': String(size),
      'Content-Disposition': `attachment; filename="${name}"`,
      'Cache-Control': 'no-store'
    }
  });
}
