import { DashboardAccessRulesUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { listAccessRules, replaceAccessRules } from '@/lib/access-rules';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
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 rules = await listAccessRules(guildId);
    return NextResponse.json({ rules });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function PUT(request: NextRequest, { params }: RouteParams) {
  const { guildId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const { rules: patch } = DashboardAccessRulesUpdateSchema.parse(body);

    const before = await listAccessRules(guildId);
    const after = await replaceAccessRules(guildId, patch);

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

    return NextResponse.json({ rules: after });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
