//! API router creation and service integration
//!
//! This module handles the creation of the API router with all feature-gated
//! service routes including auth, content, email, metrics, navigation testing, and health endpoints.

use crate::api::{create_menu_routes, nav_test_router};
use crate::config::Config;
use crate::content_loader::{create_content_loader_routes, ContentLoader};
use crate::health::create_health_routes;
use axum::Router;
use rustelo_core_lib::cache::content::ContentCache;
use std::sync::Arc;

#[cfg(feature = "auth")]
use crate::auth::routes::create_auth_routes;
#[cfg(feature = "content-db")]
use crate::content::routes::create_content_routes;
#[cfg(feature = "email")]
use crate::handlers::email::create_email_routes;
#[cfg(feature = "metrics")]
use crate::metrics::routes::create_metrics_routes;

/// Create API router with all feature-gated service routes
#[allow(unused_variables)]
pub fn create_api_router(
    config: &Config,
    app_state: &crate::app_state::AppState,
    content_cache: Arc<ContentCache>,
    #[cfg(feature = "auth")] auth_service: Arc<crate::auth::AuthService>,
    #[cfg(feature = "content-db")] content_service: Arc<crate::content::ContentService>,
    #[cfg(feature = "email")] email_service: Arc<crate::email::EmailService>,
) -> Result<axum::Router, Box<dyn std::error::Error>> {
    let mut api_router = Router::new();

    // Add menu routes (always available)
    let menu_routes = create_menu_routes();
    api_router = api_router.merge(menu_routes);

    // Add auth routes if feature is enabled
    #[cfg(feature = "auth")]
    {
        let auth_routes = create_auth_routes().with_state(auth_service);
        api_router = api_router.nest("/auth", auth_routes);
    }

    // Add content routes if feature is enabled
    #[cfg(feature = "content-db")]
    {
        let content_routes = create_content_routes().with_state(content_service);
        api_router = api_router.nest("/content", content_routes);
    }

    // Add email routes if feature is enabled
    #[cfg(feature = "email")]
    {
        let email_routes = create_email_routes().with_state(email_service);
        api_router = api_router.nest("/email", email_routes);
    }

    // Add content management API routes if content-db feature is enabled
    #[cfg(feature = "content-db")]
    {
        use crate::content::{routes::create_content_api_routes, ContentApiState};

        // Initialize content watcher if enabled
        #[cfg(feature = "content-watcher")]
        let content_api_state = {
            use crate::content::ContentWatcher;

            // Create content watcher - use unified path resolution
            let content_build_path = rustelo_core_lib::get_content_path();
            let watcher = ContentWatcher::new(
                &content_build_path,
                "scripts/content/build-localized-content.sh",
            )
            .expect("Failed to create content watcher");

            // Start watching in background
            let watcher_arc = Arc::new(watcher);
            let watcher_clone = watcher_arc.clone();
            tokio::spawn(async move {
                if let Err(e) = watcher_clone.start_watching().await {
                    tracing::error!("Failed to start content watcher: {}", e);
                } else {
                    tracing::info!("Content watcher started successfully");
                }
            });

            ContentApiState::with_watcher(watcher_arc)
        };

        #[cfg(not(feature = "content-watcher"))]
        let content_api_state = ContentApiState::new();

        let content_api_routes =
            create_content_api_routes().with_state(Arc::new(content_api_state));

        api_router = api_router.nest("/content", content_api_routes);
    }

    // Add static content meta API routes if content-static feature is enabled
    #[cfg(feature = "content-static")]
    {
        use axum::{extract::Path, http::StatusCode, response::Json, routing::get};

        let static_meta_routes = Router::new().route(
            "/meta/{content_type}/{language}",
            get(
                |Path((content_type, language)): Path<(String, String)>| async move {
                    match rustelo_core_lib::categories::load_meta_config(&content_type, &language) {
                        Ok(config) => Ok(Json(config)),
                        Err(e) => {
                            tracing::error!(
                                "Failed to load meta config for {}/{}: {}",
                                content_type,
                                language,
                                e
                            );
                            Err(StatusCode::NOT_FOUND)
                        }
                    }
                },
            ),
        );

        api_router = api_router.nest("/content", static_meta_routes);
    }

    // Add health check routes
    let health_routes = create_health_routes().with_state(app_state.clone());
    api_router = api_router.merge(health_routes);

    // Add content loader routes (always available for static content) - use unified path resolution
    let content_root = rustelo_core_lib::path_resolution::get_content_path();
    let content_loader = ContentLoader::with_cache(content_root.into(), content_cache.clone());
    let content_loader_routes = create_content_loader_routes().with_state(content_loader);
    api_router = api_router.nest("/content", content_loader_routes);

    // Add navigation test API routes (if enabled via environment variable)
    if std::env::var("ENABLE_NAV_TEST_API").unwrap_or_default() == "true" {
        let nav_test_routes = nav_test_router();
        api_router = api_router.nest("/nav-test", nav_test_routes);
        tracing::info!("Navigation test API enabled at /api/nav-test");
    }

    // Add metrics routes if feature is enabled
    #[cfg(feature = "metrics")]
    {
        if config.app.enable_metrics {
            let metrics_routes = create_metrics_routes().with_state(app_state.clone());
            api_router = api_router.merge(metrics_routes);
        }
    }

    Ok(api_router)
}
