import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { getGuildBackupRecord } from '@/lib/module-configs/guildbackup';

interface RouteParams {
  params: Promise<{ guildId: string; backupId: string }>;
}

export async function GET(_request: NextRequest, { params }: RouteParams) {
  const { guildId, backupId } = await params;
  try {
    await requireGuildAccess(guildId);
    const backup = await getGuildBackupRecord(guildId, backupId);
    if (!backup) {
      return NextResponse.json({ error: 'Backup not found' }, { status: 404 });
    }

    const filename = `nexumi-backup-${backup.name.replace(/[^a-z0-9-_]+/gi, '_')}-${backup.id}.json`;
    return new NextResponse(JSON.stringify(backup.payload, null, 2), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Content-Disposition': `attachment; filename="${filename}"`
      }
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
