// transferir_stock
// Two-input morphism. Conservation rule (Stock.cantidad grouped by sku_id)
// is enforced by the kernel against the produced ops. Same-SKU is also
// asserted in-script for an explicit error message; without that check
// the kernel would still catch the violation via per-sku grouping.
//
// states.source / states.dest: the two Stock records.
// ids.source / ids.dest:       their UUIDs.
// params: { cantidad:i64, timestamp:str, transfer_id:str }

let cantidad = input.params.cantidad;
let source = input.states.source;
let dest   = input.states.dest;

if cantidad <= 0 {
    throw "cantidad debe ser positiva"
}
if source.sku_id != dest.sku_id {
    throw "transferencia exige mismo SKU; source=" + source.sku_id + " dest=" + dest.sku_id
}
let xfr_id = input.params.transfer_id;
if type_of(xfr_id) == "()" {
    throw "params.transfer_id es obligatorio (idempotencia)"
}

[
    #{
        op: "set",
        path: #{ entity: "Stock", id: input.ids.source, field: "cantidad" },
        value: source.cantidad - cantidad,
    },
    #{
        op: "set",
        path: #{ entity: "Stock", id: input.ids.dest, field: "cantidad" },
        value: dest.cantidad + cantidad,
    },
    #{
        op: "create",
        entity: "TransferenciaStock",
        id: xfr_id,
        data: #{
            id:              xfr_id,
            source_stock_id: input.ids.source,
            dest_stock_id:   input.ids.dest,
            sku_id:          source.sku_id,
            cantidad:        cantidad,
            timestamp:       input.params.timestamp,
        },
    },
]
