//! Standardized error handling patterns for Rhai bindings

use super::error::ToRhaiError;
use rhai::EvalAltResult;

/// Standard error handling for optional operations (returns default on error)
pub fn handle_optional_result<T, F>(
    result: Result<T, super::error::ProfilingError>,
    default_fn: F,
    operation_name: &str,
) -> T
where
    F: FnOnce() -> T,
{
    match result {
        Ok(value) => value,
        Err(e) => {
            super::logging::log_error(&format!("{} failed: {}", operation_name, e));
            default_fn()
        }
    }
}

/// Standard error handling for report generation (returns fallback string on error)
pub fn handle_report_generation<T>(
    result: Result<T, super::error::ProfilingError>,
    fallback: &str,
    operation_name: &str,
) -> String
where
    T: Into<String>,
{
    match result {
        Ok(value) => value.into(),
        Err(e) => {
            super::logging::log_error(&format!("{} failed: {}", operation_name, e));
            fallback.to_string()
        }
    }
}

/// Standard error handling for system detection (returns default profile on error)
pub fn handle_system_detection<T>(
    result: Result<T, super::error::ProfilingError>,
    default: T,
    operation_name: &str,
) -> T
where
    T: Clone,
{
    match result {
        Ok(value) => value,
        Err(e) => {
            super::logging::log_error(&format!("{} failed: {}", operation_name, e));
            default
        }
    }
}

/// Convert Result to Rhai-compatible Result with proper error logging
pub fn to_rhai_result_with_logging<T>(
    result: Result<T, super::error::ProfilingError>,
    operation_name: &str,
) -> Result<T, Box<EvalAltResult>> {
    result.to_rhai_error().map_err(|e| {
        // Log the error before converting to Rhai error
        super::logging::log_error(&format!("{} failed: {}", operation_name, e));
        e
    })
}
