import { NextResponse } from 'next/server'
import { format } from 'date-fns'
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 monthStr = searchParams.get('month') || format(new Date(), 'yyyy-MM')

  const [year, month] = monthStr.split('-').map(Number)
  const start = new Date(year, month - 1, 1)
  const end = new Date(year, month, 0, 23, 59, 59)

  // Add padding for bookings that span across months
  start.setDate(start.getDate() - 7)
  end.setDate(end.getDate() + 7)

  const bookings = await prisma.booking.findMany({
    where: {
      OR: [
        { startDate: { gte: start, lte: end } },
        { endDate: { gte: start, lte: end } },
        { AND: [{ startDate: { lte: start } }, { endDate: { gte: end } }] },
      ],
    },
    select: {
      id: true,
      bookingNo: true,
      status: true,
      startDate: true,
      endDate: true,
      currency: true,
      totalAmount: true,
      query: { select: { leadName: true } },
    },
    orderBy: { startDate: 'asc' },
  })

  return NextResponse.json(bookings)
})
