//! Route validation functionality

use super::types::Route;
use std::collections::{HashMap, HashSet};

/// Validate route patterns for conflicts at build time
/// This prevents runtime panics by catching conflicting routes early
pub fn validate_route_patterns(routes: &[Route]) -> Result<(), String> {
    // Group routes by pattern to detect conflicts
    let mut route_patterns: HashMap<String, Vec<String>> = HashMap::new();
    let mut exact_routes: HashSet<String> = HashSet::new();

    for route in routes {
        if !route.enabled {
            continue;
        }

        let path = &route.path;

        // Skip external routes
        if route.is_external.unwrap_or(false) || !path.starts_with('/') {
            continue;
        }

        // Check for exact route duplicates
        if exact_routes.contains(path) {
            return Err(format!(
                "BUILD ERROR: Duplicate route found: '{}'. Each route path must be unique.",
                path
            ));
        }
        exact_routes.insert(path.clone());

        // Check for parametric route conflicts
        if path.contains('{') && path.contains('}') {
            // Normalize the pattern by replacing parameter names with a placeholder
            let normalized_pattern = normalize_route_pattern(path);

            route_patterns
                .entry(normalized_pattern.clone())
                .or_insert_with(Vec::new)
                .push(path.clone());
        }
    }

    // Check for conflicting parametric patterns
    for (pattern, paths) in route_patterns {
        if paths.len() > 1 {
            return Err(format!(
                "BUILD ERROR: Conflicting route patterns detected!\n\
                Pattern: {}\n\
                Conflicting routes: {}\n\
                \n\
                These routes would conflict at runtime because they have the same pattern.\n\
                Consider using:\n\
                - Different base paths determined from content-kinds configuration\n\
                - More specific patterns based on your content types\n\
                - Remove redundant routes\n",
                pattern,
                paths.join(", ")
            ));
        }
    }

    println!("✅ Route pattern validation passed - no conflicts detected");
    Ok(())
}

/// Normalize a route pattern for conflict detection
/// Replaces parameter names with a standardized placeholder
fn normalize_route_pattern(path: &str) -> String {
    use regex::Regex;

    // Replace all {param} patterns with {PARAM} to normalize
    let re = Regex::new(r"\{[^}]+\}").unwrap();
    re.replace_all(path, "{PARAM}").to_string()
}
