//! Menu API routes for navigation menu loading

use std::collections::HashMap;

use axum::{extract::Path, http::StatusCode, response::Json, routing::get, Router};
use serde::{Deserialize, Serialize};

/// Menu item response structure for API responses
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MenuItemResponse {
    pub route: String,
    pub label: HashMap<String, String>,
    pub icon: Option<String>,
    pub priority: Option<i32>,
    pub is_external: Option<bool>,
    pub localized_routes: Option<HashMap<String, String>>,
}

/// Get menu items for a specific language
async fn get_menu(Path(language): Path<String>) -> Result<Json<Vec<MenuItemResponse>>, StatusCode> {
    use rustelo_core_lib::load_reactive_menu_for_language;

    tracing::info!("🔧 Menu API: Fetching menu for language: '{}'", language);

    match load_reactive_menu_for_language(&language) {
        Ok(menu_items) => {
            let response: Vec<MenuItemResponse> = menu_items
                .into_iter()
                .map(|item| MenuItemResponse {
                    route: item.route,
                    label: item.label.translations,
                    icon: item.icon,
                    priority: item.priority,
                    is_external: item.is_external,
                    localized_routes: item.localized_routes,
                })
                .collect();

            tracing::info!(
                "✅ Menu API: Returning {} items for language '{}'",
                response.len(),
                language
            );
            Ok(Json(response))
        }
        Err(e) => {
            tracing::warn!(
                "⚠️ Menu API: Failed to load menu for language '{}': {}",
                language,
                e
            );
            Err(StatusCode::NOT_FOUND)
        }
    }
}

/// Create menu API routes
pub fn create_menu_routes() -> Router {
    Router::new().route("/menu/{language}", get(get_menu))
}
