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

// Server-side print for the A4 picklist PDF (dashboard "Picking" reprint).
//
// Mirrors the generic /api/print/ route (write base64 → printDispatch), but lets the
// caller pick the target CUPS queue (a paper/A4 printer from CUST_Printer) and the
// CUPS options. printDispatch whitelists both (no shell is involved any more).
//
// Body: { pathName, fileName, fileContent (base64), printer?, printOptions? }
//   printer      → CUPS queue name; defaults to 'default'.
//   printOptions → CUPS options; defaults to '-o sides=one-sided' (A4 simplex).
//   `-o media=A5|A4` is appended from the PDF page size when not given.

const SAFE_OPTIONS = /^[A-Za-z0-9=_.\- ]*$/

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)

  // Fall back to safe defaults if the value is missing or fails the whitelist.
  const printer = SAFE_QUEUE.test(body.printer || '') ? body.printer : 'default'
  const printOptions = SAFE_OPTIONS.test(body.printOptions ?? '') && body.printOptions
    ? body.printOptions
    : '-o sides=one-sided'

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

    // A5 / A4 pages get an explicit `-o media=` unless the caller set one, so the
    // A5 Lieferschein pulls A5 paper instead of the queue default.
    const page = await detectPdfPage(filePath)
    const options = withMediaOption(printOptions, page)

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

  return data
})
