// Endpoint genérico de impresión que acepta una lista de operaciones
import { buildFromOperations, type Operation } from '../../utils/eposBuilder'
import { buildSoapEnvelope, sendToPrinter, parsePrinterResponse } from '../../utils/printer'
import { getSelectedPrinter, getPrinterById } from '../../utils/printers'

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

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

    // Construir el XML interior con las operaciones
    const inner = buildFromOperations(operations)
    const soap = buildSoapEnvelope(inner)

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

    // Obtener la impresora a usar
    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
    }
  }
})
