use axum::{response::IntoResponse, Json};
use ontoref_ontology::ApiRouteEntry;
use serde_json::json;

/// GET /api/v1/catalog
///
/// Returns the annotated API catalog: all registered routes with their
/// method, path, description, auth, actors, params, and tags.
/// Populated at link time via `#[onto_api]` on each handler function.
pub async fn api_catalog() -> impl IntoResponse {
    let mut routes: Vec<&'static ApiRouteEntry> = inventory::iter::<ApiRouteEntry>().collect();
    routes.sort_by(|a, b| a.path.cmp(b.path).then(a.method.cmp(b.method)));

    let entries: Vec<_> = routes
        .into_iter()
        .map(|r| {
            json!({
                "method":      r.method,
                "path":        r.path,
                "description": r.description,
                "auth":        r.auth,
                "actors":      r.actors,
                "params":      r.params.iter().map(|p| json!({
                    "name":        p.name,
                    "kind":        p.kind,
                    "constraint":  p.constraint,
                    "description": p.description,
                })).collect::<Vec<_>>(),
                "tags":        r.tags,
            })
        })
        .collect();

    Json(json!({ "routes": entries }))
}
