//! API registry data access.
//!
//! This module provides functions for accessing API registry entries stored in the
//! athena_logging Postgres database. API registry entries define routing and configuration
//! for various APIs used by the system.

use serde_json::Value;
use sqlx::Row;
use sqlx::postgres::{PgPool, PgRow};
use sqlx::types::JsonValue;

/// Fetch all API registry entries from athena_logging.
///
/// Retrieves all API registry entries from the `api_registry` table.
///
/// # Returns
///
/// Returns `Result<Vec<Value>, String>` where:
/// - `Ok(Vec<Value>)` contains the list of API registry entries on success
/// - `Err(String)` contains a formatted error message on failure
///
/// # Example
///
/// ```ignore
/// match list_api_registry_entries(pool).await {
///     Ok(entries) => println!("Found {} entries", entries.len()),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub async fn list_api_registry_entries(pool: &PgPool) -> Result<Vec<Value>, String> {
    let rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT to_jsonb(t) AS row_json
        FROM api_registry t
        "#,
    )
    .fetch_all(pool)
    .await
    .map_err(|err| {
        format!("Failed to fetch list_api_registry_entries data from athena_logging: {err}")
    })?;

    rows.into_iter()
        .map(|row| {
            row.try_get::<JsonValue, _>("row_json").map_err(|err| {
                format!("Failed to decode list_api_registry_entries row from athena_logging: {err}")
            })
        })
        .collect::<Result<Vec<Value>, String>>()
}

/// Fetch a single API registry entry by id from athena_logging.
///
/// Retrieves a specific API registry entry from the `api_registry` table by its
/// `api_registry_id` (uuid or string identifier).
///
/// # Arguments
///
/// * `pool` - Postgres pool for the athena_logging database
/// * `api_registry_id` - The unique identifier of the API registry entry to retrieve
///
/// # Returns
///
/// Returns `Result<Vec<Value>, String>` where:
/// - `Ok(Vec<Value>)` contains the matching API registry entry on success (typically a single-element vector)
/// - `Err(String)` contains a formatted error message on failure
///
/// # Example
///
/// ```ignore
/// match get_api_registry_by_id(pool, "some-id").await {
///     Ok(entries) => println!("Found entry: {:?}", entries.first()),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub async fn get_api_registry_by_id(
    pool: &PgPool,
    api_registry_id: &str,
) -> Result<Vec<Value>, String> {
    let rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT to_jsonb(t) AS row_json
        FROM api_registry t
        WHERE t.api_registry_id::text = $1
        "#,
    )
    .bind(api_registry_id)
    .fetch_all(pool)
    .await
    .map_err(|err| {
        format!(
            "Failed to fetch api_registry by id {} from athena_logging: {:?}",
            api_registry_id, err
        )
    })?;

    rows.into_iter()
        .map(|row| {
            row.try_get::<JsonValue, _>("row_json").map_err(|err| {
                format!("Failed to decode api_registry row from athena_logging: {err}")
            })
        })
        .collect::<Result<Vec<Value>, String>>()
}
