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

export async function PATCH(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = (await request.json()) as { id?: string; reason?: string };
    if (!body.id) {
      return NextResponse.json({ error: 'Missing case id' }, { status: 400 });
    }
    const patch = CaseUpdateDashboardSchema.parse({ reason: body.reason });
    const updated = await updateCaseReason(guildId, body.id, patch);
    if (!updated) {
      return NextResponse.json({ error: 'Case not found' }, { status: 404 });
    }
    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'case.update',
      path: `/dashboard/${guildId}/moderation`,
      before: { id: body.id },
      after: updated
    });
    return NextResponse.json({ case: updated });
  } 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 case id' }, { status: 400 });
    }
    const ok = await softDeleteCase(guildId, id);
    if (!ok) {
      return NextResponse.json({ error: 'Case not found' }, { status: 404 });
    }
    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'case.delete',
      path: `/dashboard/${guildId}/moderation`,
      before: { id },
      after: { deleted: true }
    });
    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
