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

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

  const operation = await prisma.dailyOperation.findUnique({
    where: { id },
    include: {
      booking: { select: { bookingNo: true } },
    },
  })
  if (!operation) throw new AuthError('Operation not found', 404)

  return NextResponse.json(operation)
})

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

  // If driverId is being updated, auto-fill driver, vehicle, and supplier info
  let driverFields: Record<string, any> = {}
  if (data.driverId !== undefined) {
    if (data.driverId) {
      const driver = await prisma.driver.findUnique({
        where: { id: data.driverId },
        select: {
          name: true, phone: true,
          vehicle: { select: { registrationNo: true, vehicleType: true } },
          supplier: { select: { name: true, phone: true, contactPerson: true } },
        },
      })
      if (driver) {
        driverFields = {
          driverId: data.driverId,
          driverName: driver.name,
          driverPhone: driver.phone,
          vehicleNo: driver.vehicle?.registrationNo || data.vehicleNo || null,
          vehicleType: driver.vehicle?.vehicleType || data.vehicleType || null,
          supplierName: driver.supplier?.name || null,
          supplierPhone: driver.supplier?.phone || null,
          supplier2Name: driver.supplier?.contactPerson || null,
        }
      }
    } else {
      // driverId explicitly set to null — clear driver fields
      driverFields = {
        driverId: null,
        driverName: data.driverName !== undefined ? (data.driverName || null) : null,
        driverPhone: data.driverPhone !== undefined ? (data.driverPhone || null) : null,
        vehicleNo: data.vehicleNo !== undefined ? (data.vehicleNo || null) : null,
        vehicleType: data.vehicleType !== undefined ? (data.vehicleType || null) : null,
        supplierName: null,
        supplierPhone: null,
        supplier2Name: null,
      }
    }
  } else {
    // driverId not in payload — only update individual fields if provided
    if (data.driverName !== undefined) driverFields.driverName = data.driverName || null
    if (data.driverPhone !== undefined) driverFields.driverPhone = data.driverPhone || null
    if (data.vehicleNo !== undefined) driverFields.vehicleNo = data.vehicleNo || null
    if (data.vehicleType !== undefined) driverFields.vehicleType = data.vehicleType || null
  }

  const operation = await prisma.dailyOperation.update({
    where: { id },
    data: {
      bookingId: data.bookingId || undefined,
      date: data.date ? new Date(data.date) : undefined,
      operationType: data.operationType || undefined,
      title: data.title || undefined,
      description: data.description !== undefined ? (data.description || null) : undefined,
      startTime: data.startTime !== undefined ? (data.startTime || null) : undefined,
      endTime: data.endTime !== undefined ? (data.endTime || null) : undefined,
      fromLocation: data.fromLocation !== undefined ? (data.fromLocation || null) : undefined,
      toLocation: data.toLocation !== undefined ? (data.toLocation || null) : undefined,
      paxCount: data.paxCount !== undefined ? (data.paxCount ? parseInt(data.paxCount) : null) : undefined,
      adultCount: data.adultCount !== undefined ? (data.adultCount !== null && data.adultCount !== '' ? parseInt(data.adultCount) : null) : undefined,
      childCount: data.childCount !== undefined ? (data.childCount !== null && data.childCount !== '' ? parseInt(data.childCount) : null) : undefined,
      childAges: data.childAges !== undefined ? (data.childAges || null) : undefined,
      returnTime: data.returnTime !== undefined ? (data.returnTime || null) : undefined,
      supplierName: data.supplierName !== undefined ? (data.supplierName || null) : undefined,
      supplierPhone: data.supplierPhone !== undefined ? (data.supplierPhone || null) : undefined,
      supplier2Name: data.supplier2Name !== undefined ? (data.supplier2Name || null) : undefined,
      sellingPrice: data.sellingPrice !== undefined ? (data.sellingPrice !== null && data.sellingPrice !== '' ? parseFloat(data.sellingPrice) : null) : undefined,
      ticketCost: data.ticketCost !== undefined ? (data.ticketCost !== null && data.ticketCost !== '' ? parseFloat(data.ticketCost) : null) : undefined,
      costPrice1: data.costPrice1 !== undefined ? (data.costPrice1 !== null && data.costPrice1 !== '' ? parseFloat(data.costPrice1) : null) : undefined,
      costPrice2: data.costPrice2 !== undefined ? (data.costPrice2 !== null && data.costPrice2 !== '' ? parseFloat(data.costPrice2) : null) : undefined,
      agentName: data.agentName !== undefined ? (data.agentName || null) : undefined,
      bookingPerson: data.bookingPerson !== undefined ? (data.bookingPerson || null) : undefined,
      country: data.country !== undefined ? (data.country || null) : undefined,
      guestName: data.guestName !== undefined ? (data.guestName || null) : undefined,
      status: data.status || undefined,
      notes: data.notes !== undefined ? (data.notes || null) : undefined,
      ...driverFields,
    },
  })

  return NextResponse.json(operation)
})

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

  const operation = await prisma.dailyOperation.findUnique({ where: { id } })
  if (!operation) throw new AuthError('Operation not found', 404)
  if (operation.status !== 'SCHEDULED') throw new AuthError('Only SCHEDULED operations can be deleted', 400)

  await prisma.dailyOperation.delete({ where: { id } })
  return NextResponse.json({ message: 'Deleted' })
})
