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

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

export const GET = safeHandler(async (_req: Request, { params }: Params) => {
  await requireAuth()
  const { id } = await params

  const bookings = await prisma.sICTourBooking.findMany({
    where: { sicTourId: id },
    include: {
      booking: {
        select: {
          bookingNo: true,
          query: { select: { leadName: true } },
        },
      },
    },
    orderBy: { createdAt: 'desc' },
  })

  return NextResponse.json(bookings)
})

export const POST = safeHandler(async (req: Request, { params }: Params) => {
  await requireAuth(['ADMIN', 'OPERATIONS'])
  const { id } = await params
  const data = await req.json()

  if (!data.bookingId) {
    throw new AuthError('Booking ID is required', 400)
  }

  const paxCount = data.paxCount || 1

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

  if (tour.status === 'CANCELLED' || tour.status === 'COMPLETED') {
    throw new AuthError(`Cannot add bookings to a ${tour.status.toLowerCase()} tour`, 400)
  }

  if (tour.currentBookings + paxCount > tour.maxCapacity) {
    throw new AuthError(
      `Not enough capacity. Available: ${tour.maxCapacity - tour.currentBookings}, Requested: ${paxCount}`,
      400
    )
  }

  const result = await prisma.$transaction(async (tx) => {
    const sicTourBooking = await tx.sICTourBooking.create({
      data: {
        sicTourId: id,
        bookingId: data.bookingId,
        paxCount,
      },
      include: {
        booking: {
          select: {
            bookingNo: true,
            query: { select: { leadName: true } },
          },
        },
      },
    })

    const newCurrentBookings = tour.currentBookings + paxCount
    await tx.sICTour.update({
      where: { id },
      data: {
        currentBookings: newCurrentBookings,
        status: newCurrentBookings >= tour.maxCapacity ? 'FULL' : undefined,
      },
    })

    return sicTourBooking
  })

  return NextResponse.json(result, { status: 201 })
})
