import { SuggestionActionSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { applySuggestionAction, SuggestionActionTimeoutError } from '@/lib/module-configs/suggestions';
import { prisma } from '@/lib/prisma';

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

export async function POST(request: NextRequest, { params }: RouteParams) {
  const { guildId, suggestionId } = await params;
  try {
    const session = await requireGuildAccess(guildId);
    const body = await request.json();
    const action = SuggestionActionSchema.parse(body);

    const after = await applySuggestionAction(guildId, suggestionId, action, session.user.id);

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

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