// vender
// Cross-module morphism: decreases Stock (inventory) and increases Caja
// (treasury). NOT conservation-bound — a sale is asymmetric: units leave
// the system, money enters. The kernel validates each entity against its
// own schema (Stock from inventory, Caja from treasury, Venta from sales).
//
// states.stock: the Stock record (inventory module).
// states.caja:  the Caja record (treasury module).
// params: { cantidad:i64, precio_unitario:i64 (en centavos),
//           timestamp:str, venta_id:str }

let cantidad = input.params.cantidad;
let precio   = input.params.precio_unitario;
let venta_id = input.params.venta_id;

if cantidad <= 0 { throw "cantidad debe ser positiva" }
if precio   <= 0 { throw "precio_unitario debe ser positivo" }
if type_of(venta_id) == "()" { throw "params.venta_id es obligatorio (idempotencia)" }

let stock = input.states.stock;
let caja  = input.states.caja;

let total = cantidad * precio;

[
    #{
        op: "set",
        path: #{ entity: "Stock", id: input.ids.stock, field: "cantidad" },
        value: stock.cantidad - cantidad,
    },
    #{
        op: "set",
        path: #{ entity: "Caja", id: input.ids.caja, field: "saldo" },
        value: caja.saldo + total,
    },
    #{
        op: "create",
        entity: "Venta",
        id: venta_id,
        data: #{
            id:              venta_id,
            stock_id:        input.ids.stock,
            caja_id:         input.ids.caja,
            sku_id:          stock.sku_id,
            cantidad:        cantidad,
            precio_unitario: precio,
            currency:        caja.currency,
            total:           total,
            timestamp:       input.params.timestamp,
        },
    },
]
