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')

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

    const { stdout, stderr } = await exec(`lp -d labelprinter-2 -o fit-to-page ${filePath}/${fileName}`);

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

  return data
})