import { WarningListQuerySchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { deleteWarning, listWarnings } from '@/lib/module-configs/warnings';
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 query = WarningListQuerySchema.parse(Object.fromEntries(request.nextUrl.searchParams));
    const warnings = await listWarnings(guildId, query);
    return NextResponse.json({ warnings });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function DELETE(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const id = request.nextUrl.searchParams.get('id');
    if (!id) {
      return NextResponse.json({ error: 'Missing warning id' }, { status: 400 });
    }
    const ok = await deleteWarning(guildId, id);
    if (!ok) {
      return NextResponse.json({ error: 'Warning not found' }, { status: 404 });
    }
    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'warning.delete',
      path: `/dashboard/${guildId}/moderation`,
      before: { id },
      after: { deleted: true }
    });
    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
