import { VerificationConfigDashboardPatchSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  getVerificationDashboard,
  updateVerificationDashboard,
  VerificationPanelSyncError
} from '@/lib/module-configs/verification';
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 payload = await getVerificationDashboard(guildId);
    return NextResponse.json(payload);
  } 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();
    const patch = VerificationConfigDashboardPatchSchema.parse(body);

    const before = await getVerificationDashboard(guildId);
    const afterConfig = await updateVerificationDashboard(guildId, patch);
    const after = {
      config: afterConfig,
      availableCaptchaProviders: before.availableCaptchaProviders
    };

    await writeDashboardAudit(prisma, {
      guildId,
      actorUserId: session.user.id,
      action: 'verification.update',
      path: `/dashboard/${guildId}/verification`,
      before: before.config,
      after: afterConfig
    });

    return NextResponse.json(after);
  } catch (error) {
    if (error instanceof VerificationPanelSyncError) {
      return NextResponse.json(
        { error: error.message, code: error.code },
        { status: error.code === 'timeout' ? 504 : 502 }
      );
    }
    return toApiErrorResponse(error);
  }
}
