import { GuildBackupPayloadSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { deleteGuildBackupDashboard, getGuildBackupRecord } from '@/lib/module-configs/guildbackup';
import { prisma } from '@/lib/prisma';

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 parsed = GuildBackupPayloadSchema.safeParse(backup.payload);
    return NextResponse.json({
      id: backup.id,
      name: backup.name,
      createdById: backup.createdById,
      createdAt: backup.createdAt.toISOString(),
      payload: parsed.success ? parsed.data : null
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'guildbackup.delete',
      path: `/dashboard/${guildId}/backup`,
      before: { backupId }
    });

    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
