import { CommandOverrideDashboardUpsertSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { resetCommandOverrideDashboard, upsertCommandOverrideDashboard } from '@/lib/module-configs/commands';
import { prisma } from '@/lib/prisma';

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

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

    const updated = await upsertCommandOverrideDashboard(guildId, input);

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

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

export async function DELETE(_request: NextRequest, { params }: RouteParams) {
  const { guildId, commandName } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const reset = await resetCommandOverrideDashboard(guildId, commandName);

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

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