//! Parameter extraction utilities for routing
//!
//! This module provides methods for extracting parameters from route patterns
//! and matching them against actual paths.

use std::collections::HashMap;

/// Extract parameter from route pattern (language-agnostic)
///
/// Finds single parameter placeholders in the route pattern like
/// `/{content_type}/{slug}`
pub fn extract_parameter_from_route(
    route_pattern: &str,
    actual_path: &str,
) -> Option<(String, String)> {
    // Find parameter placeholders in the route pattern
    if let Some(start) = route_pattern.find('{') {
        if let Some(end) = route_pattern.find('}') {
            if start < end {
                let parameter_name = route_pattern[start + 1..end].to_string();
                let prefix = &route_pattern[..start];
                let suffix = &route_pattern[end + 1..];

                // Check if the actual path matches the pattern
                if actual_path.starts_with(prefix) && actual_path.ends_with(suffix) {
                    let parameter_start = prefix.len();
                    let parameter_end = actual_path.len() - suffix.len();

                    if parameter_start <= parameter_end {
                        let parameter_value =
                            actual_path[parameter_start..parameter_end].to_string();
                        if !parameter_value.is_empty() && !parameter_value.contains('/') {
                            return Some((parameter_name, parameter_value));
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract multiple parameters from route pattern
///
/// Handles patterns like `/{content_type}/{category}/{slug}` by splitting on
/// path segments and matching parameter placeholders.
pub fn extract_multiple_parameters(
    route_pattern: &str,
    actual_path: &str,
) -> Option<HashMap<String, String>> {
    let pattern_parts: Vec<&str> = route_pattern.split('/').collect();
    let path_parts: Vec<&str> = actual_path.split('/').collect();

    if pattern_parts.len() != path_parts.len() {
        return None;
    }

    let mut parameters = HashMap::new();

    for (pattern_part, path_part) in pattern_parts.iter().zip(path_parts.iter()) {
        if pattern_part.starts_with('{') && pattern_part.ends_with('}') {
            // This is a parameter placeholder
            let param_name = &pattern_part[1..pattern_part.len() - 1];
            parameters.insert(param_name.to_string(), path_part.to_string());
        } else if pattern_part != path_part {
            // Non-parameter part doesn't match
            return None;
        }
    }

    if parameters.is_empty() {
        None
    } else {
        Some(parameters)
    }
}
