import { GuildBackupCreateDashboardSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { createGuildBackupDashboard, BackupPremiumError, listGuildBackupsDashboard } from '@/lib/module-configs/guildbackup';
import { prisma } from '@/lib/prisma';

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

export async function GET(_request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    await requireGuildAccess(guildId);
    const backups = await listGuildBackupsDashboard(guildId);
    return NextResponse.json({ backups });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const input = GuildBackupCreateDashboardSchema.parse(body);

    const backup = await createGuildBackupDashboard(guildId, input.name, session.user.id);

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

    return NextResponse.json(backup, { status: 201 });
  } catch (error) {
    if (error instanceof BackupPremiumError) {
      return NextResponse.json({ error: error.code }, { status: 403 });
    }
    return toApiErrorResponse(error);
  }
}
