use server::config::Config;
use std::env;

fn main() {
    println!("Testing configuration loading...");

    // Test 1: Configuration with auto-creation enabled
    println!("\n=== Test 1: Auto-creation enabled ===");

    // Set environment variables BEFORE Config::load()
    unsafe {
        env::set_var("ENVIRONMENT", "development");
        env::set_var("AUTO_CREATE_CONFIG", "true");
    }

    // Try to load configuration
    match Config::load() {
        Ok(config) => {
            println!("✅ Configuration loaded successfully!");
            println!("Server: {}:{}", config.server.host, config.server.port);
            println!("Environment: {:?}", config.server.environment);
            println!("Debug mode: {}", config.app.debug);
            println!("Database URL: {}", config.database.url);
            println!("Log level: {}", config.server.log_level);
        }
        Err(e) => {
            println!("❌ Failed to load configuration: {}", e);
            std::process::exit(1);
        }
    }

    // Check if config file was created
    if std::path::Path::new("config.dev.toml").exists() {
        println!("✅ Default config file 'config.dev.toml' was created");

        // Clean up for next test
        if let Err(e) = std::fs::remove_file("config.dev.toml") {
            println!("⚠️  Could not clean up config file: {}", e);
        }
    } else if std::path::Path::new("config.toml").exists() {
        println!("✅ Default config file 'config.toml' exists");
    } else {
        println!("⚠️  No config file found, running with in-memory defaults");
    }

    // Test 2: Configuration with auto-creation disabled
    println!("\n=== Test 2: Auto-creation disabled ===");

    // Set environment variables to disable auto-creation
    unsafe {
        env::set_var("ENVIRONMENT", "development");
        env::set_var("AUTO_CREATE_CONFIG", "false");
    }

    // Try to load configuration again
    match Config::load() {
        Ok(config) => {
            println!("✅ Configuration loaded successfully with auto-creation disabled!");
            println!("Server: {}:{}", config.server.host, config.server.port);
            println!("Environment: {:?}", config.server.environment);
            println!("Debug mode: {}", config.app.debug);
            println!("Database URL: {}", config.database.url);
            println!("Log level: {}", config.server.log_level);
        }
        Err(e) => {
            println!("❌ Failed to load configuration: {}", e);
            std::process::exit(1);
        }
    }

    // Check that no config file was created
    if std::path::Path::new("config.dev.toml").exists() {
        println!("❌ Config file was created despite AUTO_CREATE_CONFIG=false");
    } else {
        println!("✅ No config file created when auto-creation is disabled");
    }

    println!("\n=== All tests completed ===");
}
