use std::env;

use rustelo_server::config::Config;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize tracing
    tracing_subscriber::fmt::init();

    println!("Testing database configuration...");

    // Test 1: SQLite configuration
    println!("\n=== Test 1: SQLite Configuration ===");
    test_sqlite_config().await?;

    // Test 2: PostgreSQL configuration
    println!("\n=== Test 2: PostgreSQL Configuration ===");
    test_postgresql_config().await?;

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

async fn test_sqlite_config() -> Result<(), Box<dyn std::error::Error>> {
    unsafe {
        env::set_var("ENVIRONMENT", "development");
        env::set_var("AUTO_CREATE_CONFIG", "true");
    }

    let config = Config::load()?;
    println!("SQLite configuration loaded:");
    println!("  Database URL: {}", config.database.url);
    println!("  Max connections: {}", config.database.max_connections);

    if config.database.url.starts_with("sqlite:") {
        println!("✅ SQLite configuration detected");

        // Create data directory
        if let Some(path) = config.database.url.strip_prefix("sqlite:") {
            if let Some(parent) = std::path::Path::new(path).parent() {
                std::fs::create_dir_all(parent)?;
                println!("✅ Database directory created: {}", parent.display());
            }
        }
    } else {
        println!("⚠️  Expected SQLite URL but got: {}", config.database.url);
    }

    Ok(())
}

async fn test_postgresql_config() -> Result<(), Box<dyn std::error::Error>> {
    // Temporarily modify config to use PostgreSQL
    unsafe {
        env::set_var("ENVIRONMENT", "development");
        env::set_var("AUTO_CREATE_CONFIG", "false");
    }

    let mut config = Config::load()?;
    config.database.url = "postgresql://postgres:password@localhost:5432/rustelo_dev".to_string();

    println!("PostgreSQL configuration:");
    println!("  Database URL: {}", config.database.url);
    println!("  Max connections: {}", config.database.max_connections);

    if config.database.url.starts_with("postgresql://")
        || config.database.url.starts_with("postgres://")
    {
        println!("✅ PostgreSQL configuration detected");
        println!("  Note: Actual connection would require PostgreSQL to be running");
        println!("  To set up PostgreSQL:");
        println!("    1. Install PostgreSQL locally");
        println!("    2. Create database: createdb rustelo_dev");
        println!(
            "    3. Or use Docker: docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password \
             postgres"
        );
    } else {
        println!(
            "⚠️  Expected PostgreSQL URL but got: {}",
            config.database.url
        );
    }

    Ok(())
}
