//! 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_web::{HttpResponse, Responder, get, web::Data};
// use tracing::info;

pub mod admin;
pub mod auth;
pub mod backup;
pub mod cache;
pub mod client_context;
pub mod error;
pub mod gateway;
pub mod headers;
pub mod health;
pub mod host_routing;
pub mod management;
pub mod metrics;
pub mod pg_meta;
pub mod pipelines;
pub mod provision;
pub mod public_routes;
pub mod query;
pub mod registry;
pub mod response;
pub mod schema;
pub mod storage;
pub mod supabase;

pub use error::{ApiError, ApiResult};

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

const OPENAPI_YAML: &str = include_str!("../../openapi.yaml");
const OPENAPI_WSS_YAML: &str = include_str!("../../openapi-wss.yaml");

/// 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(state: Data<AppState>) -> impl Responder {
    let pool: sqlx::Pool<sqlx::Postgres> = match logging_pool(&state) {
        Ok(pool) => pool,
        Err(resp) => return resp,
    };

    match list_athena_router_entries(&pool).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.
///
#[get("/openapi.yaml")]
pub async fn athena_openapi_host() -> impl Responder {
    HttpResponse::Ok()
        .content_type("application/yaml; charset=utf-8")
        .body(OPENAPI_YAML)
}

/// Serves the bundled `openapi-wss.yaml` so clients can download the WebSocket spec.
#[get("/openapi-wss.yaml")]
pub async fn athena_wss_openapi_host() -> impl Responder {
    HttpResponse::Ok()
        .content_type("application/yaml; charset=utf-8")
        .body(OPENAPI_WSS_YAML)
}

/// 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()
}

// All mount points for the api will be moved to here with just a simple abstraction function that's called to reference it's logic
