import { NextResponse } from 'next/server'
import { renderToBuffer } from '@react-pdf/renderer'
import { prisma } from '@/lib/prisma'
import { safeHandler, requireAuth, AuthError } from '@/lib/auth'
import { VoucherPDFDocument } from '@/lib/pdf-templates/voucher-pdf'

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

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

  const url = new URL(req.url)
  const type = (url.searchParams.get('type') || 'FULL_TOUR') as 'FULL_TOUR' | 'HOTEL_ONLY'

  if (!['FULL_TOUR', 'HOTEL_ONLY'].includes(type)) {
    throw new AuthError('Invalid voucher type. Use FULL_TOUR or HOTEL_ONLY', 400)
  }

  const booking = await prisma.booking.findUnique({
    where: { id },
    include: {
      query: {
        select: {
          leadName: true,
          leadEmail: true,
          leadPhone: true,
          adults: true,
          children: true,
          infants: true,
        },
      },
      passengers: {
        orderBy: { sortOrder: 'asc' },
      },
      itineraryDays: {
        orderBy: { dayNumber: 'asc' },
        include: {
          items: {
            orderBy: { sortOrder: 'asc' },
            include: {
              hotel: { select: { name: true } },
            },
          },
        },
      },
      bookingItems: {
        orderBy: { sortOrder: 'asc' },
        include: {
          hotel: { select: { name: true } },
        },
      },
      operations: {
        orderBy: { date: 'asc' },
      },
    },
  })

  if (!booking) throw new AuthError('Booking not found', 404)

  const company = await prisma.companySettings.findUnique({
    where: { id: 'default' },
  })

  const buffer = await renderToBuffer(
    VoucherPDFDocument({ booking, company, type })
  )

  const filename = `${booking.bookingNo}-${type === 'HOTEL_ONLY' ? 'hotel-voucher' : 'tour-voucher'}.pdf`

  return new NextResponse(buffer, {
    status: 200,
    headers: {
      'Content-Type': 'application/pdf',
      'Content-Disposition': `inline; filename="${filename}"`,
      'Cache-Control': 'no-store',
    },
  })
})
