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

use serde_json::Value;
use supabase_rs::SupabaseClient;
// use tracing::error;

use crate::data::suitsbooks_supabase;

/// Fetch all API registry entries from Supabase.
///
/// Retrieves all API registry entries from the `api_registry` table in the Suitsbooks
/// Supabase project.
///
/// # 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().await {
///     Ok(entries) => println!("Found {} entries", entries.len()),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub async fn list_api_registry_entries() -> Result<Vec<Value>, String> {
    let client: SupabaseClient = suitsbooks_supabase().await;

    let data: Result<Vec<Value>, String> = client
        .select("api_registry")
        .columns(["*"].to_vec())
        .execute()
        .await;

    match data {
        Ok(result) => Ok(result),
        Err(err) => Err(format!(
            "Failed to fetch list_api_registry_entries data: {:?}",
            err
        )),
    }
}

/// Fetch a single API registry entry by id from Supabase.
///
/// Retrieves a specific API registry entry from the `api_registry` table by its
/// `api_registry_id`.
///
/// # Arguments
///
/// * `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("some-id").await {
///     Ok(entries) => println!("Found entry: {:?}", entries.first()),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub async fn get_api_registry_by_id(api_registry_id: &str) -> Result<Vec<Value>, String> {
    let client: SupabaseClient = suitsbooks_supabase().await;

    let data: Result<Vec<Value>, String> = client
        .select("api_registry")
        .columns(["*"].to_vec())
        .eq("api_registry_id", api_registry_id)
        .execute()
        .await;

    match data {
        Ok(result) => Ok(result),
        Err(err) => Err(format!(
            "Failed to fetch api_registry by id {}: {:?}",
            api_registry_id, err
        )),
    }
}
