// Endpoint para imprimir operaciones arbitrarias con variables inline
import { buildFromOperations } from '../../utils/eposBuilder'
import { buildSoapEnvelope, sendToPrinter, parsePrinterResponse } from '../../utils/printer'
import { getSelectedPrinter, getPrinterById } from '../../utils/printers'
import { resolveVariables, Operation } from '../../utils/templates'

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

    const {
      operations,
      variables = {},
      dryRun = false,
      printerId
    } = body as {
      operations: Operation[]
      variables?: Record<string, string>
      dryRun?: boolean
      printerId?: string
    }

    // Validar operations
    if (!operations || !Array.isArray(operations) || operations.length === 0) {
      return {
        ok: false,
        error: 'operations es requerido y debe ser un array no vacío'
      }
    }

    // Resolver variables en las operaciones
    const resolvedOperations = resolveVariables(operations, variables)

    // Construir el XML
    const inner = buildFromOperations(resolvedOperations)
    const soap = buildSoapEnvelope(inner)

    // Si es dryRun, devolver sin enviar a la impresora
    if (dryRun) {
      return {
        ok: true,
        dryRun: true,
        soap,
        resolvedOperations
      }
    }

    // Obtener la impresora
    let printer = printerId
      ? await getPrinterById(printerId)
      : await getSelectedPrinter()

    if (!printer) {
      return {
        ok: false,
        error: 'No hay impresora configurada. Por favor, agrega una impresora primero.'
      }
    }

    // Enviar a la impresora
    const result = await sendToPrinter(
      soap,
      printer.host,
      printer.deviceId,
      printer.timeout
    )

    // Parsear la respuesta
    const { success, code } = parsePrinterResponse(result.data)

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