// Endpoint para cortar papel
import { buildFromOperations } from '../../utils/eposBuilder'
import { buildSoapEnvelope, sendToPrinter, parsePrinterResponse } from '../../utils/printer'

export default defineEventHandler(async (event) => {
  try {
    const config = useRuntimeConfig()
    const body = await readBody(event)

    const { type = 'feed' } = body as { type?: string }

    const inner = buildFromOperations([{ op: 'cut', type }])
    const soap = buildSoapEnvelope(inner)

    const result = await sendToPrinter(
      soap,
      config.printerHost,
      config.printerDeviceId,
      parseInt(config.printerTimeoutMs)
    )

    const { success, code } = parsePrinterResponse(result.data)

    return {
      ok: success,
      httpStatus: result.status,
      code,
      raw: result.data
    }
  } catch (err: any) {
    return {
      ok: false,
      error: err.message
    }
  }
})
