import { ModulesUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { getModuleStatuses, updateModuleStatuses } from '@/lib/modules';
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 modules = await getModuleStatuses(guildId);
    return NextResponse.json({ modules });
  } 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 { modules: patch } = ModulesUpdateSchema.parse(body);

    const before = await getModuleStatuses(guildId);
    const after = await updateModuleStatuses(guildId, patch);

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

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