// Endpoint para abrir cajón de dinero
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 { drawer, time } = body as {
      drawer?: string
      time?: string
    }

    const inner = buildFromOperations([{ op: 'pulse', drawer, time }])
    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
    }
  }
})
