import { detectPdfPage, withMediaOption } from '../../utils/pdfPageMedia'
import { stagePrintFile, printFile, applyPrintResult } from '../../utils/printDispatch'

// Generic "print this PDF on the default paper queue" (document print pages' server-print button).
export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)

  try {
    const filePath = await stagePrintFile(body.pathName, body.fileName, Buffer.from(body.fileContent, 'base64'))

    // Explicit `-o media=A5|A4` from the PDF page size (see server/utils/pdfPageMedia.ts).
    const page = await detectPdfPage(filePath)
    const options = withMediaOption('-o sides=one-sided', page)

    const result = await printFile(event, { queue: 'default', options, filePath, source: 'print/index' })
    data = applyPrintResult({ ...body, pageKind: page.kind }, result)
    data['printOptions'] = options
  } catch(err: any) {
    data = err
  }

  return data
})
