use robson_plugin_implementation_workflow::WorkflowConfig;
use std::sync::{Mutex, OnceLock};

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

fn env_lock() -> std::sync::MutexGuard<'static, ()> {
    ENV_MUTEX.get_or_init(|| Mutex::new(())).lock().unwrap()
}

#[test]
fn test_workflow_from_env_orchestrator() {
    let _guard = env_lock();

    std::env::set_var("ROBSON_AGENT_CONCURRENCY", "4");
    std::env::set_var("ROBSON_AGENT_DB_PATH", "/data/core.db");
    std::env::set_var("ROBSON_AGENT_WEBHOOK_PORT", "8080");
    std::env::set_var("ROBSON_AGENT_GIT_NAME", "Bot");
    std::env::set_var("ROBSON_AGENT_GIT_EMAIL", "bot@example.com");
    std::env::set_var("ROBSON_AGENT_PARALLEL_WORKERS", "true");
    std::env::set_var("ROBSON_AGENT_TMP_DIR", "/tmp/robson");
    std::env::remove_var("ROBSON_AGENT_CLAUDE_BIN");
    std::env::remove_var("ROBSON_AGENT_API_TOKEN");
    std::env::remove_var("ROBSON_AGENT_SSH_KEY_PATH");

    let cfg = WorkflowConfig::from_env();

    std::env::remove_var("ROBSON_AGENT_CONCURRENCY");
    std::env::remove_var("ROBSON_AGENT_DB_PATH");
    std::env::remove_var("ROBSON_AGENT_WEBHOOK_PORT");
    std::env::remove_var("ROBSON_AGENT_GIT_NAME");
    std::env::remove_var("ROBSON_AGENT_GIT_EMAIL");
    std::env::remove_var("ROBSON_AGENT_PARALLEL_WORKERS");
    std::env::remove_var("ROBSON_AGENT_TMP_DIR");

    assert_eq!(cfg.orchestrator.concurrency, 4);
    assert_eq!(cfg.orchestrator.db_path, "/data/core.db");
    assert_eq!(cfg.orchestrator.webhook_port, 8080);
    assert_eq!(cfg.orchestrator.git_name, "Bot");
    assert_eq!(cfg.orchestrator.git_email, "bot@example.com");
    assert!(cfg.orchestrator.parallel_workers);
    assert_eq!(cfg.orchestrator.tmp_dir, "/tmp/robson");
    assert_eq!(cfg.orchestrator.claude_bin, None);
    assert_eq!(cfg.orchestrator.api_token, None);
    assert_eq!(cfg.orchestrator.ssh_key_path, None);
}

#[test]
fn test_workflow_from_env_defaults() {
    let _guard = env_lock();

    std::env::remove_var("ROBSON_AGENT_CONCURRENCY");
    std::env::remove_var("ROBSON_AGENT_DB_PATH");
    std::env::remove_var("ROBSON_AGENT_WEBHOOK_PORT");
    std::env::remove_var("ROBSON_AGENT_GIT_NAME");
    std::env::remove_var("ROBSON_AGENT_GIT_EMAIL");
    std::env::remove_var("ROBSON_AGENT_PARALLEL_WORKERS");
    std::env::remove_var("ROBSON_AGENT_TMP_DIR");
    std::env::remove_var("ROBSON_WORKFLOW_DB_PATH");

    let cfg = WorkflowConfig::from_env();

    assert_eq!(cfg.orchestrator.concurrency, 1);
    assert_eq!(cfg.orchestrator.db_path, "robson-core.db");
    assert_eq!(cfg.orchestrator.webhook_port, 3000);
    assert_eq!(cfg.orchestrator.git_name, "Robson Agent");
    assert_eq!(cfg.orchestrator.git_email, "queiroz@investtools.com.br");
    assert!(!cfg.orchestrator.parallel_workers);
    assert_eq!(cfg.orchestrator.tmp_dir, ".tmp");
    assert_eq!(cfg.workflow.db_path, "robson-workflow.db");
}
