import { BirthdayConfigDashboardPatchSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { getBirthdayDashboard, updateBirthdayDashboard } from '@/lib/module-configs/birthdays';
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 config = await getBirthdayDashboard(guildId);
    return NextResponse.json(config);
  } 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 = BirthdayConfigDashboardPatchSchema.parse(body);

    const before = await getBirthdayDashboard(guildId);
    const after = await updateBirthdayDashboard(guildId, patch);

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

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