// Endpoint de conveniencia para imprimir texto con opciones
import { buildFromOperations, type Operation } 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 {
      text = '',
      options = {}
    } = body as {
      text?: string
      options?: {
        align?: string
        font?: string
        size?: { width?: number, height?: number }
        style?: {
          reverse?: boolean
          ul?: boolean
          em?: boolean
          color?: string
        }
        feedLines?: number
        cut?: string
      }
    }

    // Construir operaciones
    const ops: Operation[] = []

    if (options.align) {
      ops.push({ op: 'textAlign', align: options.align })
    }
    if (options.font) {
      ops.push({ op: 'textFont', font: options.font })
    }
    if (options.size) {
      ops.push({
        op: 'textSize',
        width: options.size.width,
        height: options.size.height
      })
    }
    if (options.style) {
      ops.push({ op: 'textStyle', ...options.style })
    }

    // Agregar el texto
    ops.push({ op: 'text', value: text })

    // Opciones post-texto
    if (options.feedLines) {
      ops.push({ op: 'feedLine', line: options.feedLines })
    }
    if (options.cut) {
      ops.push({ op: 'cut', type: options.cut })
    }

    // Construir SOAP y enviar
    const inner = buildFromOperations(ops)
    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
    }
  }
})
