import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { safeHandler, requireAuth, AuthError } from '@/lib/auth'

type Params = { params: Promise<{ id: string; bookingId: string }> }

export const DELETE = safeHandler(async (_req: Request, { params }: Params) => {
  await requireAuth(['ADMIN', 'OPERATIONS'])
  const { id, bookingId } = await params

  const sicTourBooking = await prisma.sICTourBooking.findUnique({
    where: { sicTourId_bookingId: { sicTourId: id, bookingId } },
  })

  if (!sicTourBooking) {
    throw new AuthError('Booking not found in this tour', 404)
  }

  const tour = await prisma.sICTour.findUnique({ where: { id } })
  if (!tour) throw new AuthError('SIC Tour not found', 404)

  await prisma.$transaction(async (tx) => {
    await tx.sICTourBooking.delete({
      where: { sicTourId_bookingId: { sicTourId: id, bookingId } },
    })

    const newCurrentBookings = tour.currentBookings - sicTourBooking.paxCount
    await tx.sICTour.update({
      where: { id },
      data: {
        currentBookings: Math.max(0, newCurrentBookings),
        status: tour.status === 'FULL' && newCurrentBookings < tour.maxCapacity ? 'ACTIVE' : undefined,
      },
    })
  })

  return NextResponse.json({ success: true })
})
