//! Error handling for WASM bindings.
//!
//! Maps internal error types to JavaScript exceptions with human-readable messages.

use entropyk::ThermoError;
use wasm_bindgen::JsValue;

/// Convert a Result to a Result with JsValue error.
pub fn result_to_js<T, E: std::fmt::Display>(result: Result<T, E>) -> Result<T, JsValue> {
    result.map_err(|e| js_sys::Error::new(&e.to_string()).into())
}

/// Map ThermoError to a human-readable JsValue.
pub fn thermo_error_to_js(e: ThermoError) -> JsValue {
    let msg = match &e {
        ThermoError::Component(err) => format!("Component error: {}", err),
        ThermoError::Solver(err) => format!("Solver error: {}", err),
        ThermoError::Fluid(err) => format!("Fluid error: {}", err),
        ThermoError::Topology(err) => format!("Topology error: {}", err),
        ThermoError::AddEdge(err) => format!("Edge error: {}", err),
        ThermoError::Connection(err) => format!("Connection error: {}", err),
        ThermoError::Constraint(err) => format!("Constraint error: {}", err),
        _ => format!("{}", e),
    };
    js_sys::Error::new(&msg).into()
}
