import { TicketDashboardActionSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  applyTicketDashboardAction,
  TicketActionSyncError
} from '@/lib/module-configs/tickets';
import { prisma } from '@/lib/prisma';

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

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

    const after = await applyTicketDashboardAction(
      guildId,
      ticketId,
      action,
      session.user.id
    );
    if (!after) {
      return NextResponse.json({ error: 'Ticket not found' }, { status: 404 });
    }

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

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