//! Eval implementation for the transform function

use hamelin_lib::func::defs::Transform;

use crate::eval::evaluator::invoke_closure;
use crate::registry::EvalRegistry;
use crate::value::Value;

/// Register the transform function eval implementation.
pub fn register(registry: &mut EvalRegistry) {
    // transform(array, lambda) - apply lambda to each element
    registry.register_eval::<Transform>(|mut bindings| {
        let array_value = bindings.take_by_name("array")?;
        let closure_value = bindings.take_by_name("lambda")?;

        // Handle null array
        if array_value.is_null() {
            return Ok(Value::Null);
        }

        let elements = array_value.require_array()?;
        let closure = closure_value.require_closure()?;

        // Apply closure to each element
        let mut results = Vec::with_capacity(elements.len());
        for elem in elements {
            let result = invoke_closure(&closure, vec![elem])?;
            results.push(result);
        }

        Ok(Value::Array(results))
    });
}
