import { TicketCategoryDashboardUpdateSchema } from '@nexumi/shared';
import { type NextRequest, NextResponse } from 'next/server';
import { requireGuildAccess, toApiErrorResponse } from '@/lib/auth';
import { writeDashboardAudit } from '@/lib/audit';
import {
  deleteTicketCategory,
  TicketCategoryConflictError,
  TicketPanelSyncError,
  updateTicketCategory
} from '@/lib/module-configs/tickets';
import { prisma } from '@/lib/prisma';

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

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

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

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

    return NextResponse.json(updated);
  } 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);
  }
}

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

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

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