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

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')
  const shippingPrinter = body.shippingPrinter || 'labelprinter-1'
  const printOptions = body.printOptions || '' // Optional print options (e.g., '-o sides=one-sided')

  try {
    if(!existsSync(filePath)) {
      mkdirSync(filePath, { recursive: true })
    }
    await writeFile(`${filePath}/${fileName}`, fileContent)
    // await exec(`pdfjam --outfile ${filePath}/a6_${fileName} --paper a6paper --scale 1.2 ${filePath}/${fileName}`)

    // const { stdout, stderr } = await exec(`lp -o page-top=40 -o page-bottom=-30 -d label ${filePath}/a6_${fileName}`);
    const { stdout, stderr } = await exec(`lp -d ${shippingPrinter} ${printOptions} ${filePath}/${fileName}`);


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

  return data
})