//! Tests for DevService

use mecha10_cli::services::dev::DevService;
use std::net::TcpListener;
use std::path::PathBuf;

#[test]
fn test_service_creation() {
    let service = DevService::new("redis://test:6379".to_string());
    assert_eq!(service.redis_url, "redis://test:6379");
}

#[test]
fn test_default_service() {
    let service = DevService::default();
    assert_eq!(service.redis_url, "redis://localhost:6379");
}

#[test]
fn test_is_port_available() {
    let service = DevService::default();

    // Bind to a port to make it unavailable
    let _listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
    let port = _listener.local_addr().unwrap().port();

    // Port should not be available
    assert!(!service.is_port_available(port).unwrap());
    assert!(service.is_port_in_use(port).unwrap());
}

#[test]
fn test_get_default_env_vars() {
    let service = DevService::new("redis://custom:6379".to_string());
    let env = service.get_default_env_vars();

    assert_eq!(env.get("REDIS_URL"), Some(&"redis://custom:6379".to_string()));
    assert_eq!(env.get("RUST_LOG"), Some(&"info".to_string()));
}

#[test]
fn test_build_godot_args() {
    let service = DevService::default();
    let project_path = PathBuf::from("/path/to/project");
    let model_path = PathBuf::from("/path/to/model");
    let env_path = PathBuf::from("/path/to/env");

    // Test without headless
    let args = service.build_godot_args(&project_path, &model_path, &env_path, None, None, false);

    assert_eq!(args.len(), 5);
    assert_eq!(args[0], "--path");
    assert_eq!(args[1], "/path/to/project");
    assert_eq!(args[2], "--");
    assert!(args[3].starts_with("--env-path="));
    assert!(args[4].starts_with("--model-path="));

    // Test with headless
    let args_headless = service.build_godot_args(&project_path, &model_path, &env_path, None, None, true);

    assert_eq!(args_headless.len(), 6);
    assert_eq!(args_headless[0], "--path");
    assert_eq!(args_headless[1], "/path/to/project");
    assert_eq!(args_headless[2], "--headless");
    assert_eq!(args_headless[3], "--");
    assert!(args_headless[4].starts_with("--env-path="));
    assert!(args_headless[5].starts_with("--model-path="));
}

#[test]
fn test_get_godot_project_path_default() {
    let service = DevService::default();
    let path = service.get_godot_project_path();

    // Without MECHA10_FRAMEWORK_PATH, should use relative path
    assert_eq!(path, PathBuf::from("simulation/godot"));
}
