import { TicketCategoryDashboardCreateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import { createTicketCategory, listTicketCategories, TicketCategoryConflictError, TicketPanelSyncError } from '@/lib/module-configs/tickets';
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 categories = await listTicketCategories(guildId);
    return NextResponse.json({ categories });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

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

    const category = await createTicketCategory(guildId, input);

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

    return NextResponse.json(category, { status: 201 });
  } catch (error) {
    if (error instanceof TicketCategoryConflictError) {
      return NextResponse.json({ error: error.message }, { status: 409 });
    }
    if (error instanceof TicketPanelSyncError) {
      return NextResponse.json(
        { error: error.message, code: error.code },
        { status: error.code === 'timeout' ? 504 : 502 }
      );
    }
    return toApiErrorResponse(error);
  }
}
