/**
 * POST /api/offers/quote/preview
 * Body: OfferQuotePayload (built client-side by useOfferQuote/buildQuotePayload).
 * Renders the branded Angebot PDF and returns it as base64 for the modal's
 * iframe preview — nothing is sent or persisted here.
 */
import refreshTokenHelper from '../../../utils/refreshTokenHelper'
import errorHandlingHelper from '../../../utils/errorHandlingHelper'
import forceLogoutHelper from '../../../utils/forceLogoutHelper'
import { generateQuotePdf } from '../../../utils/offers/quotePdf'

const handleFunc = async (event: any, authToken: string | null = null) => {
  // Auth gate only — the PDF is rendered purely from the posted payload.
  const token = authToken ?? await getTokenHelper(event)
  if (!token) return { status: 401, message: 'Not authenticated' }

  const body = await readBody(event)
  if (!body?.customer?.company || !body?.customer?.contactName) {
    return { status: 400, message: 'Company and contact name are required' }
  }

  const { buffer, filename } = await generateQuotePdf(body)
  return { status: 200, pdfBase64: buffer.toString('base64'), filename }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }
  return data
})
