//! Content validation utilities for routing
//!
//! This module provides methods for checking content existence
//! and validating content-related routes.

/// Generic content existence checker - works with any content type
/// Uses the generated content type system to validate content existence
pub fn content_exists(content_type: &str, slug: &str, _language: &str) -> bool {
    content_exists_with_category(content_type, slug, _language, None)
}

/// Content existence checker with optional category support
pub fn content_exists_with_category(
    content_type: &str,
    slug: &str,
    _language: &str,
    category: Option<&str>,
) -> bool {
    #[cfg(target_arch = "wasm32")]
    web_sys::console::log_1(
        &format!(
            "🚨🚨🚨 CONTENT_EXISTS ENTRY POINT: type='{}', slug='{}', language='{}', category='{}'",
            content_type,
            slug,
            _language,
            category.unwrap_or("None")
        )
        .into(),
    );
    // First check if this is a valid content type from the generated registry
    #[cfg(target_arch = "wasm32")]
    web_sys::console::log_1(&format!("🚨 CONTENT_EXISTS: Getting all content types...").into());

    let valid_content_types = crate::generated_access::get_all_content_types();

    #[cfg(target_arch = "wasm32")]
    web_sys::console::log_1(
        &format!("🚨 CONTENT_EXISTS: Valid types: {:?}", valid_content_types).into(),
    );

    if !valid_content_types.contains(&content_type.to_string()) {
        #[cfg(not(target_arch = "wasm32"))]
        tracing::warn!(
            "🔍 Unknown content type '{}' - not in generated registry",
            content_type
        );

        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(
            &format!(
                "🚨 CONTENT_EXISTS: Invalid content type '{}', returning false",
                content_type
            )
            .into(),
        );

        return false;
    }

    #[cfg(target_arch = "wasm32")]
    web_sys::console::log_1(
        &format!(
            "🚨 CONTENT_EXISTS: Content type '{}' is valid",
            content_type
        )
        .into(),
    );

    // Check if this slug is actually a valid category for this content type
    // TODO: Category validation removed during routing crate extraction
    // This should be re-added through a trait-based abstraction that allows
    // the content crate to provide category validation without tight coupling
    //
    // Only use category validation in SSR mode where it's reliable
    // #[cfg(not(target_arch = "wasm32"))]
    // {
    //     if crate::categories::is_valid_category(content_type, slug) {
    //         // If it's a valid category, it's NOT a content item
    //         return false;
    //     }
    // }

    // Basic slug validation that applies to all content types
    let is_valid_slug = !slug.is_empty()
        && slug.len() > 3
        && slug
            .chars()
            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
        && !slug.starts_with('-')
        && !slug.ends_with('-');

    if !is_valid_slug {
        return false;
    }

    #[cfg(target_arch = "wasm32")]
    {
        // For WASM, we can try to load the content index if available
        // This is a generic approach that could work for any content type
        web_sys::console::log_1(
            &format!(
                "🔍 WASM: Checking {} content exists: slug='{}', language='{}' - is_valid_slug: {}",
                content_type, slug, _language, is_valid_slug
            )
            .into(),
        );

        // Get valid content types for validation
        let valid_content_types = crate::generated_access::get_all_content_types();
        let is_valid_content_type = valid_content_types.contains(&content_type.to_string());

        web_sys::console::log_1(
            &format!(
                "🔍 WASM: Content type '{}' is valid: {}, valid types: {:?}",
                content_type, is_valid_content_type, valid_content_types
            )
            .into(),
        );

        // During hydration, be more permissive to avoid hydration mismatches
        // If the server rendered the content, it must exist
        let is_hydrating = web_sys::window()
            .and_then(|w| w.document())
            .map(|doc| {
                doc.body()
                    .map(|body| body.get_attribute("data-hydrating").is_some())
                    .unwrap_or(false)
            })
            .unwrap_or(false);

        let result = if is_hydrating {
            // During hydration, trust that if the server rendered it, it exists
            // This prevents hydration mismatches
            web_sys::console::log_1(
                &format!(
                    "🔍 WASM: Hydration mode - trusting server-side validation for slug: '{}'",
                    slug
                )
                .into(),
            );
            is_valid_content_type && is_valid_slug
        } else {
            // After hydration, use normal validation
            is_valid_content_type && is_valid_slug
        };

        web_sys::console::log_1(
            &format!(
                "🔍 WASM: Final content_exists result: {} (is_hydrating: {}, \
                 is_valid_content_type: {}, is_valid_slug: {})",
                result, is_hydrating, is_valid_content_type, is_valid_slug
            )
            .into(),
        );

        #[cfg(target_arch = "wasm32")]
        web_sys::console::log_1(&format!("🚨🚨🚨 CONTENT_EXISTS RETURNING: {}", result).into());

        result
    }

    #[cfg(not(target_arch = "wasm32"))]
    {
        // For SSR, check if the built HTML content file exists in the public directory
        let server_root =
            std::env::var("SITE_SERVER_ROOT_CONTENT").unwrap_or_else(|_| "r".to_string());

        let mut content_file_path = std::path::PathBuf::from("public")
            .join(&server_root)
            .join(content_type)
            .join(_language);

        // Add category directory if provided
        if let Some(cat) = category {
            content_file_path = content_file_path.join(cat);
        }

        content_file_path = content_file_path.join(format!("{}.html", slug));

        let exists = content_file_path.exists();

        tracing::debug!(
            "🔍 SSR: Checking {} content at: {:?} - exists: {}",
            content_type,
            content_file_path,
            exists
        );

        exists
    }
}
