use std::ffi::OsString;
use std::sync::{Mutex, MutexGuard};

static ENV_MUTEX: Mutex<()> = Mutex::new(());

/// RAII guard that sets an env var and restores the old value on drop.
/// The global ENV_MUTEX is held across the test body so parallel tests cannot
/// race on process-global environment variables like HOME.
pub struct EnvGuard {
    key: &'static str,
    old: Option<OsString>,
    _lock: MutexGuard<'static, ()>,
}

impl EnvGuard {
    pub fn set(key: &'static str, value: &str) -> Self {
        let lock = ENV_MUTEX.lock().expect("env mutex poisoned");
        let old = std::env::var_os(key);
        // SAFETY: serialized via ENV_MUTEX; only one test mutates env at a time.
        unsafe { std::env::set_var(key, value) };
        Self {
            key,
            old,
            _lock: lock,
        }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        if let Some(v) = &self.old {
            unsafe { std::env::set_var(self.key, v) };
        } else {
            unsafe { std::env::remove_var(self.key) };
        }
    }
}
