import { getPortfolio } from '../../../lib/portfolio-store'
import { generatePdf } from '../../../lib/pdf-pipeline'

// Génération séquentielle : une seule instance Chromium à la fois.
let queue: Promise<unknown> = Promise.resolve()

export default defineEventHandler(async (event) => {
  const portfolio = await getPortfolio(getRouterParam(event, 'id')!)
  if (!portfolio) throw createError({ statusCode: 404, statusMessage: 'Portfolio introuvable' })

  const { fileName } = await readBody<{ fileName?: string }>(event).catch(() => ({ fileName: undefined }))

  const run = queue.then(() => generatePdf(portfolio, fileName))
  queue = run.catch(() => {})
  try {
    return await run
  } catch (err) {
    throw createError({
      statusCode: 500,
      statusMessage: `Échec de la génération : ${err instanceof Error ? err.message : String(err)}`,
    })
  }
})
