//! Request handlers for routing and fallback handling
//!
//! This module contains various request handlers including the fallback handler
//! for dynamic routes and other specialized request handling functions.

use crate::run::{render_ssr_with_context, render_ssr_with_route_resolution};
use axum::{
    extract::State,
    http::HeaderMap,
    response::{IntoResponse, Response},
};
use leptos::prelude::*;
use rustelo_core_lib::routing::engine::resolve_route;

/// Fallback handler for dynamic routes (blog posts, etc.)
/// Uses the shared routing engine to resolve routes and render appropriate responses
pub async fn fallback_handler(
    State(leptos_options): State<LeptosOptions>,
    headers: HeaderMap,
    uri: axum::http::Uri,
) -> Response {
    let path = uri.path();

    tracing::debug!("Fallback handler processing path: {}", path);

    // Use the shared routing engine to resolve the route
    let route_resolution = resolve_route(path);

    if route_resolution.exists {
        // Route exists - detect language and handle redirects if needed
        let detected_lang = crate::utils::lang_detection::detect_ssr_language(path, &headers);

        // Check if we need to redirect to the localized version (language-agnostic)
        if let Some(localized_url) =
            crate::utils::lang_detection::check_language_redirect(path, &detected_lang, &headers)
        {
            tracing::debug!(
                "Redirecting {} to localized version ({}): {}",
                path,
                detected_lang,
                localized_url
            );
            return axum::response::Response::builder()
                .status(302) // Temporary redirect
                .header("Location", localized_url)
                .body(axum::body::Body::empty())
                .unwrap()
                .into_response();
        }

        // Route exists - render it using the routing engine's resolution
        tracing::debug!("Route exists, rendering with SSR: {}", path);

        // Check if the routing engine provided a specific component resolution
        if let Some(component) = &route_resolution.component {
            tracing::debug!(
                "Using routing engine component: {:?} with parameters: {:?}",
                component,
                route_resolution.parameters
            );

            // Create a custom SSR render that respects the routing engine's decision
            axum::response::Html(render_ssr_with_route_resolution(
                leptos_options,
                &route_resolution,
            ))
            .into_response()
        } else {
            // Fallback to standard Leptos SSR routing
            tracing::debug!(
                "No specific component from routing engine, using standard SSR: {}",
                path
            );
            axum::response::Html(render_ssr_with_context(
                leptos_options,
                Some(path.to_string()),
            ))
            .into_response()
        }
    } else {
        // Route doesn't exist - return 404
        tracing::debug!("Route not found: {}", path);

        // Create a proper 404 page using Leptos SSR with proper arena context
        let not_found_html =
            render_ssr_with_context(leptos_options, Some("/not-found".to_string()));

        axum::response::Response::builder()
            .status(404)
            .header("Content-Type", "text/html; charset=utf-8")
            .body(axum::body::Body::from(not_found_html))
            .unwrap()
            .into_response()
    }
}
