//! Public HTTP API routes for Athena RS.
//!
//! This module wires REST endpoints for the router registry and query execution.
//!
//! ## Endpoints
//!
//! - `GET /router/registry` - Retrieve all Athena router registry entries

use actix_files::NamedFile;
use actix_web::{Responder, get};
// use tracing::info;

pub mod cache;
pub mod gateway;
pub mod headers;
pub mod pipelines;
pub mod query;
pub mod registry;
pub mod response;
pub mod schema;
pub mod supabase;

// crate imports
use crate::data::athena_router::list_athena_router_entries;
use response::{api_ok, internal_error};

/// List Athena router registry entries.
///
/// Fetches all router entries from the Athena router registry and returns them as a JSON response.
///
/// # Returns
///
/// Returns an HTTP response containing either:
/// - Success (200): A JSON array of all router entries
/// - Error (500): An error message if the fetch operation fails
#[get("/router/registry")]
pub async fn athena_router_registry() -> impl Responder {
    match list_athena_router_entries().await {
        Ok(entries) => api_ok(entries),
        Err(err) => internal_error("Failed to list router entries", err),
    }
}

/// Serves the bundled `openapi.yaml` so clients can download the latest spec.
///
/// Returns `500 Internal Server Error` if the file cannot be read (which should not happen
/// in production, since the file is packaged with the binary).
#[get("/openapi.yaml")]
pub async fn athena_openapi_host() -> actix_web::Result<NamedFile> {
    NamedFile::open("openapi.yaml").map_err(|err| {
        actix_web::error::ErrorInternalServerError(format!("Failed to open openapi.yaml: {}", err))
    })
}

/// Redirects `/docs` to the public Athena documentation site.
///
/// Issues a 308 permanent redirect so browsers/crawlers can follow the canonical documentation URL.
#[get("/docs")]
pub async fn athena_docs() -> impl Responder {
    actix_web::HttpResponse::PermanentRedirect()
        .insert_header(("Location", "https://xylex.group/docs/athena"))
        .finish()
}
