//! Common middleware utilities for API servers

use axum::http::header::*;
use axum::http::Method;
use tower_http::cors::{AllowOrigin, CorsLayer};

/// Create a CORS layer with default settings
///
/// Allows:
/// - All origins (*)
/// - GET, POST, PUT, DELETE methods
/// - Content-Type header
/// - All response headers
pub fn cors_layer() -> CorsLayer {
    CorsLayer::permissive()
}

/// Create a CORS layer with specific allowed origins
///
/// # Arguments
/// * `origins` - List of allowed origins (e.g., ["http://localhost:3000"])
pub fn cors_layer_with_origins(origins: Vec<&str>) -> CorsLayer {
    let allow_origin: Vec<_> = origins
        .iter()
        .filter_map(|origin| origin.parse::<http::Uri>().ok())
        .map(|uri| {
            uri.to_string()
                .parse()
                .expect("Valid URI should parse to HeaderValue")
        })
        .collect();

    CorsLayer::new()
        .allow_origin(AllowOrigin::list(allow_origin))
        .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
        .allow_headers([CONTENT_TYPE])
}

/// Initialize logging with the given log level
///
/// # Arguments
/// * `log_level` - Log level as string (e.g., "info", "debug", "warn")
pub fn init_logging(log_level: &str) {
    use tracing_subscriber::EnvFilter;

    let env_filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(log_level));

    tracing_subscriber::fmt()
        .with_env_filter(env_filter)
        .with_target(true)
        .with_level(true)
        .init();

    tracing::info!("Logging initialized with level: {}", log_level);
}

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

    #[test]
    fn test_cors_layer_creation() {
        let _cors = cors_layer();
        // If we got here, cors layer was created successfully
    }

    #[test]
    fn test_cors_layer_with_origins() {
        let origins = vec!["http://localhost:3000", "http://localhost:5000"];
        let _cors = cors_layer_with_origins(origins);
        // If we got here, cors layer with origins was created successfully
    }
}
