import { SelfRolePanelDashboardUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  deleteSelfRolePanel,
  SelfRolePanelSyncError,
  updateSelfRolePanel
} from '@/lib/module-configs/selfroles';
import { prisma } from '@/lib/prisma';

interface RouteParams {
  params: Promise<{ guildId: string; panelId: string }>;
}

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

    const updated = await updateSelfRolePanel(guildId, panelId, patch);
    if (!updated) {
      return NextResponse.json({ error: 'Panel not found' }, { status: 404 });
    }

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

    return NextResponse.json(updated);
  } catch (error) {
    if (error instanceof SelfRolePanelSyncError) {
      return NextResponse.json({ error: error.message }, { status: 504 });
    }
    return toApiErrorResponse(error);
  }
}

export async function DELETE(_request: NextRequest, { params }: RouteParams) {
  const { guildId, panelId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const deleted = await deleteSelfRolePanel(guildId, panelId);
    if (!deleted) {
      return NextResponse.json({ error: 'Panel not found' }, { status: 404 });
    }

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

    return NextResponse.json({ ok: true });
  } catch (error) {
    if (error instanceof SelfRolePanelSyncError) {
      return NextResponse.json({ error: error.message }, { status: 504 });
    }
    return toApiErrorResponse(error);
  }
}
