//! Configuration module tests
//!
//! This module contains all tests for the configuration system.

#[cfg(test)]
mod config_tests {
    use super::super::*;

    #[test]
    fn test_config_loading() {
        // JSON representation mirrors nickel export output — serde_json is the
        // actual deserialisation path used by Config::load() after NCL export.
        let json = r#"{
          "server":      { "protocol": "http", "host": "127.0.0.1", "port": 3030, "environment": "development", "log_level": "info" },
          "database":    { "url": "postgresql://test:test@localhost:5432/test_db", "max_connections": 10, "min_connections": 1, "connect_timeout": 30, "idle_timeout": 600, "max_lifetime": 1800, "create_if_missing": false },
          "session":     { "secret": "test-secret-key", "cookie_name": "session_id", "cookie_secure": false, "cookie_http_only": true, "cookie_same_site": "lax", "max_age": 3600 },
          "cors":        { "allowed_origins": ["http://localhost:3030"], "allowed_methods": ["GET","POST"], "allowed_headers": ["Content-Type"], "allow_credentials": true, "max_age": 3600 },
          "static":      { "assets_dir": "public", "site_root": "target/site", "site_pkg_dir": "pkg" },
          "security":    { "enable_csrf": true, "csrf_token_name": "csrf_token", "rate_limit_requests": 100, "rate_limit_window": 60, "bcrypt_cost": 12 },
          "oauth":       { "enabled": false },
          "email":       { "enabled": false, "provider": "console", "smtp_host": "smtp.gmail.com", "smtp_port": 587, "smtp_username": "", "smtp_password": "", "smtp_use_tls": false, "smtp_use_starttls": true, "sendgrid_api_key": "", "sendgrid_endpoint": "https://api.sendgrid.com/v3/mail/send", "from_email": "", "from_name": "Test App" },
          "redis":       { "enabled": false, "url": "redis://localhost:6379", "pool_size": 10, "connection_timeout": 5, "command_timeout": 5 },
          "app":         { "name": "Test App", "version": "0.1.0", "debug": true, "enable_metrics": false, "enable_health_check": true, "enable_compression": true, "max_request_size": 10485760 },
          "logging":     { "format": "json", "level": "info", "file_path": "logs/app.log", "max_file_size": 10485760, "max_files": 5, "enable_console": true, "enable_file": false },
          "cache":       { "persistent_enabled": false, "memory_enabled": true, "memory_max_size": 104857600, "memory_ttl": 3600, "persistent_ttl": 86400, "persistent_max_size": 1073741824, "persistent_cleanup_interval": 3600 },
          "server_dirs": { "public_dir": "public", "uploads_dir": "uploads", "logs_dir": "logs", "temp_dir": "tmp", "cache_dir": "cache", "config_dir": "config", "data_dir": "data", "backup_dir": "backups" },
          "features": {
            "auth":        { "enabled": true,  "jwt": true,  "oauth": false, "two_factor": false, "sessions": true,  "password_reset": true,  "email_verification": false },
            "rbac":        { "enabled": false, "database_access": false, "file_access": false, "content_access": false, "api_access": false, "categories": false, "tags": false, "caching": false, "audit_logging": false, "toml_config": false, "hierarchical_permissions": false, "dynamic_rules": false },
            "content":     { "enabled": true,  "markdown": true, "syntax_highlighting": false, "file_uploads": true, "versioning": false, "scheduling": false, "seo": true },
            "security":    { "csrf": true, "security_headers": true, "rate_limiting": true, "input_sanitization": true, "sql_injection_protection": true, "xss_protection": true, "content_security_policy": true },
            "performance": { "response_caching": true, "query_caching": true, "compression": true, "connection_pooling": true, "lazy_loading": false, "background_tasks": true },
            "custom": {}
          }
        }"#;

        let config: Config = serde_json::from_str(json).expect("Failed to deserialise Config");
        assert_eq!(config.server.host, "127.0.0.1");
        assert_eq!(config.server.port, 3030);
        assert_eq!(config.app.name, "Test App");
    }

    #[test]
    fn test_env_substitution() {
        // Test with a string that has no substitution variables
        let input_no_vars = "postgresql://user:password@localhost:5432/db";
        let result_no_vars = Config::substitute_env_in_string(input_no_vars);
        assert_eq!(
            result_no_vars,
            "postgresql://user:password@localhost:5432/db"
        );

        // Test with PATH environment variable which should exist
        let input_with_path = "Location: ${PATH}";
        let result_with_path = Config::substitute_env_in_string(input_with_path);
        // Should contain "Location: " followed by the PATH value
        assert!(result_with_path.starts_with("Location: "));
        assert!(result_with_path.len() > "Location: ".len());

        // Test with non-existent environment variable
        let input_with_nonexistent = "Value: ${NONEXISTENT_VAR_12345}";
        let result_with_nonexistent = Config::substitute_env_in_string(input_with_nonexistent);
        // Should remain unchanged when variable doesn't exist
        assert_eq!(result_with_nonexistent, "Value: ${NONEXISTENT_VAR_12345}");
    }
}
