import { stagePrintFile, printFile, applyPrintResult, SAFE_QUEUE } from '../../utils/printDispatch'

// Attachment PDF that IS a label (e.g. a marketplace-provided shipping label) → label printer, fit-to-page.
export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)
  // Unsafe queue names fall back to the default label printer (legacy behaviour).
  const shippingPrinter = SAFE_QUEUE.test(String(body.shippingPrinter || '')) ? String(body.shippingPrinter) : 'labelprinter-1'

  try {
    const filePath = await stagePrintFile(body.pathName, body.fileName, Buffer.from(body.fileContent, 'base64'))
    const result = await printFile(event, { queue: shippingPrinter, options: '-o fit-to-page', filePath, source: 'print/attachment-labels' })
    data = applyPrintResult({ ...body }, result)
  } catch(err: any) {
    data = err
  }

  return data
})
