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

export const GET = safeHandler(async (req: Request) => {
  await requireAuth()
  const { searchParams } = new URL(req.url)

  const from = searchParams.get('from') || new Date().toISOString().slice(0, 10)
  const to = searchParams.get('to') || new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 10)
  const hotelFilter = searchParams.get('hotel') || ''
  const destinationFilter = searchParams.get('destination') || ''

  // Fetch hotel booking items where the itinerary day falls within the date range
  const items = await prisma.bookingItem.findMany({
    where: {
      serviceType: 'HOTEL',
      hotelId: hotelFilter ? hotelFilter : undefined,
      hotel: destinationFilter ? { destination: { id: destinationFilter } } : undefined,
      itineraryDay: {
        date: {
          gte: new Date(from + 'T00:00:00.000Z'),
          lte: new Date(to + 'T23:59:59.999Z'),
        },
      },
    },
    include: {
      hotel: { select: { name: true, destination: { select: { name: true } } } },
      booking: {
        select: {
          bookingNo: true,
          status: true,
          startDate: true,
          endDate: true,
          query: { select: { leadName: true } },
        },
      },
      itineraryDay: { select: { date: true, dayNumber: true } },
    },
    orderBy: { itineraryDay: { date: 'asc' } },
  })

  // Fetch related daily operations (CHECKIN / CHECKOUT) in the date range for status cross-reference
  const operations = await prisma.dailyOperation.findMany({
    where: {
      operationType: { in: ['CHECKIN', 'CHECKOUT'] },
      date: {
        gte: new Date(from + 'T00:00:00.000Z'),
        lte: new Date(to + 'T23:59:59.999Z'),
      },
    },
    select: {
      bookingId: true,
      operationType: true,
      status: true,
      guestName: true,
      location: true,
      date: true,
      booking: { select: { bookingNo: true } },
    },
  })

  // Build a lookup: bookingId -> latest operation status
  const operationStatusMap: Record<string, string> = {}
  for (const op of operations) {
    // Use the operation status (e.g. SCHEDULED, COMPLETED, etc.)
    // Prefer CHECKIN status; if CHECKOUT exists it means they already checked in
    const key = op.bookingId
    if (!operationStatusMap[key] || op.operationType === 'CHECKIN') {
      operationStatusMap[key] = op.status
    }
  }

  // Transform into check-in/check-out records
  const records = items.map((item) => {
    const checkInDate = item.itineraryDay?.date || item.booking.startDate
    const nights = item.quantity || 1
    const checkOutDate = new Date(new Date(checkInDate).getTime() + nights * 86400000)

    // Determine status: prefer daily operation status, fallback to supplierStatus, then booking status
    const opStatus = operationStatusMap[item.bookingId]
    let status = item.supplierStatus || item.booking.status
    if (opStatus) {
      status = opStatus
    }

    return {
      id: item.id,
      guestName: item.booking.query.leadName,
      hotelName: item.hotel?.name || item.description,
      destination: item.hotel?.destination?.name || '',
      checkInDate,
      checkOutDate,
      nights,
      confirmationNo: item.confirmationNo || '',
      status,
      bookingNo: item.booking.bookingNo,
      bookingId: item.bookingId,
    }
  })

  return NextResponse.json(records)
})
