import { promisify } from 'node:util'
import child_process from 'node:child_process'
import { existsSync, mkdirSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'

// Server-side print for the A4 picklist PDF (dashboard "Picking" reprint).
//
// Mirrors the generic /api/print/ route (write base64 → CUPS `lp`), but lets the
// caller pick the target CUPS queue (a paper/A4 printer from CUST_Printer) and the
// CUPS options. Both are whitelisted before being interpolated into the shell
// command so a crafted printer name / option string can't inject extra commands.
//
// 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).

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

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)
  const exec = promisify(child_process.exec)
  const pathName = body.pathName
  const filePath = `/root/storage/${pathName}`
  const fileName = body.fileName
  const fileContent = Buffer.from(body.fileContent, 'base64')

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

  try {
    if(!existsSync(filePath)) {
      mkdirSync(filePath, { recursive: true })
    }
    await writeFile(`${filePath}/${fileName}`, fileContent)

    const { stdout, stderr } = await exec(`lp -d ${printer} ${printOptions} ${filePath}/${fileName}`)

    data = body
    data['message'] = !stderr ? 'success' : 'failed'
    data['printer'] = printer
    data['stdout'] = stdout
    data['stderr'] = stderr
  } catch(err: any) {
    data = err
  }

  return data
})
