use std::sync::Arc;

use axum::{routing::get, Router};
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;

use crate::api::handlers;

/// Build application routes
pub fn build_routes(state: handlers::AppState) -> Router {
    let state = Arc::new(state);

    // API routes
    let api_routes = Router::new()
        // Extension operations
        .route("/extensions", get(handlers::list_extensions))
        .route("/extensions/search", get(handlers::search_extensions))
        .route("/extensions/{type}/{name}", get(handlers::get_extension))
        .route(
            "/extensions/{type}/{name}/versions",
            get(handlers::list_versions),
        )
        .route(
            "/extensions/{type}/{name}/{version}",
            get(handlers::download_extension),
        )
        // System endpoints
        .route("/health", get(handlers::health_check))
        .route("/metrics", get(handlers::metrics))
        .route("/cache/stats", get(handlers::cache_stats))
        .with_state(state);

    // Apply middleware
    Router::new()
        .nest("/api/v1", api_routes)
        .layer(
            CorsLayer::new()
                .allow_origin(Any)
                .allow_methods(Any)
                .allow_headers(Any),
        )
        .layer(TraceLayer::new_for_http())
}
