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

export const PUT = safeHandler(async (req: Request, { params }: { params: Promise<{ id: string; itemId: string }> }) => {
  await requireAuth()
  const { id, itemId } = await params
  const data = await req.json()

  const quantity = data.quantity !== undefined ? data.quantity : undefined
  const unitCost = data.unitCost !== undefined ? data.unitCost : undefined

  // Build update data
  const updateData: Record<string, unknown> = {}
  if (data.serviceType !== undefined) updateData.serviceType = data.serviceType
  if (data.description !== undefined) updateData.description = data.description
  if (data.itineraryDayId !== undefined) updateData.itineraryDayId = data.itineraryDayId
  if (data.notes !== undefined) updateData.notes = data.notes
  if (data.sortOrder !== undefined) updateData.sortOrder = data.sortOrder

  if (quantity !== undefined) updateData.quantity = quantity
  if (unitCost !== undefined) updateData.unitCost = unitCost

  // If both quantity and unitCost are provided, recalculate totalCost
  if (quantity !== undefined && unitCost !== undefined) {
    updateData.totalCost = quantity * unitCost
  } else if (quantity !== undefined || unitCost !== undefined) {
    // Need to fetch current values to recalculate
    const current = await prisma.bookingItem.findUnique({ where: { id: itemId } })
    if (current) {
      const q = quantity !== undefined ? quantity : current.quantity
      const u = unitCost !== undefined ? unitCost : Number(current.unitCost)
      updateData.totalCost = q * u
    }
  }

  const item = await prisma.bookingItem.update({
    where: { id: itemId },
    data: updateData,
  })

  // Recalculate booking totalAmount
  const sum = await prisma.bookingItem.aggregate({
    where: { bookingId: id },
    _sum: { totalCost: true },
  })
  await prisma.booking.update({
    where: { id },
    data: { totalAmount: sum._sum.totalCost || 0 },
  })

  return NextResponse.json(item)
})

export const DELETE = safeHandler(async (_req: Request, { params }: { params: Promise<{ id: string; itemId: string }> }) => {
  await requireAuth()
  const { id, itemId } = await params

  await prisma.bookingItem.delete({ where: { id: itemId } })

  // Recalculate booking totalAmount
  const sum = await prisma.bookingItem.aggregate({
    where: { bookingId: id },
    _sum: { totalCost: true },
  })
  await prisma.booking.update({
    where: { id },
    data: { totalAmount: sum._sum.totalCost || 0 },
  })

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