// crates/tauri-loop/src/commands/env_vars.rs
use crate::state::LoopState;
use tauri::State;

// Pure logic functions — testable without Tauri runtime
pub fn set_env_inner(state: &LoopState, key: String, value: serde_json::Value) {
    state.set_env(key, value);
}

pub fn get_env_inner(state: &LoopState, key: &str) -> Option<serde_json::Value> {
    state.get_env(key)
}

#[tauri::command]
pub fn loop_set_env(
    key: String,
    value: serde_json::Value,
    state: State<LoopState>,
) -> Result<(), String> {
    set_env_inner(&state, key, value);
    Ok(())
}

#[tauri::command]
pub fn loop_get_env(
    key: String,
    state: State<LoopState>,
) -> Result<Option<serde_json::Value>, String> {
    Ok(get_env_inner(&state, &key))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::LoopState;
    use std::path::PathBuf;

    fn make_state() -> LoopState {
        LoopState::new(PathBuf::from("/fake"), Default::default(), vec![])
    }

    #[test]
    fn set_and_get_env() {
        let state = make_state();
        set_env_inner(&state, "speed".into(), serde_json::json!(200));
        let val = get_env_inner(&state, "speed").unwrap();
        assert_eq!(val, serde_json::json!(200));
    }

    #[test]
    fn get_missing_env_returns_none() {
        let state = make_state();
        assert!(get_env_inner(&state, "missing").is_none());
    }
}
