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

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

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

  const invoice = await prisma.invoice.findUnique({
    where: { id },
    include: {
      items: { orderBy: { sortOrder: 'asc' } },
      booking: {
        select: { bookingNo: true, query: { select: { leadName: true } } },
      },
      createdBy: {
        select: { name: true, email: true },
      },
    },
  })
  if (!invoice) throw new AuthError('Invoice not found', 404)

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

  const buffer = await renderToBuffer(
    InvoicePDFDocument({ invoice, company })
  )

  const filename = `${invoice.invoiceNo}.pdf`

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