//! Athena router data access.
//!
//! This module provides functions for accessing Athena router entries stored in the
//! `athena_logging` Postgres client. Router entries define routing configurations
//! used by the Athena system.

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

/// Fetch all Athena router entries from `athena_logging`.
///
/// Retrieves all router entries from the `pm_athena_router` table.
///
/// # Returns
///
/// Returns `Result<Vec<Value>, String>` where:
/// - `Ok(Vec<Value>)` contains the list of router entries on success
/// - `Err(String)` contains a formatted error message on failure
///
/// # Example
///
/// ```ignore
/// # use sqlx::postgres::PgPool;
/// # async fn demo(pool: &PgPool) {
/// match list_athena_router_entries(pool).await {
///     Ok(entries) => println!("Found {} entries", entries.len()),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// # }
/// ```
pub async fn list_athena_router_entries(pool: &PgPool) -> Result<Vec<Value>, String> {
    let rows: Vec<PgRow> = sqlx::query(
        r#"
        SELECT to_jsonb(t) AS row_json
        FROM pm_athena_router t
        "#,
    )
    .fetch_all(pool)
    .await
    .map_err(|err| {
        format!("Failed to fetch list_athena_router_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_athena_router_entries row from athena_logging: {err}"
                )
            })
        })
        .collect::<Result<Vec<Value>, String>>()
}
