use serde::Serialize;
use sqlx::postgres::PgPool;

#[derive(Debug, Clone, Serialize)]
pub struct ClusterMirrorRecord {
    pub url: String,
    pub is_active: bool,
    pub priority: i32,
}

pub const DEFAULT_CLUSTER_MIRRORS: &[&str] = &[
    "https://athena-db.com",
    "https://mirror1.athena-db.com",
    "https://mirror2.athena-db.com",
    "https://mirror3.athena-db.com",
];

pub async fn list_active_cluster_mirrors(
    pool: &PgPool,
) -> Result<Vec<ClusterMirrorRecord>, sqlx::Error> {
    let rows = sqlx::query(
        r#"
        SELECT url, is_active, priority
        FROM cluster_mirrors
        WHERE is_active = true
        ORDER BY priority ASC, url ASC
        "#,
    )
    .fetch_all(pool)
    .await?;

    Ok(rows
        .into_iter()
        .map(|row| ClusterMirrorRecord {
            url: sqlx::Row::get(&row, "url"),
            is_active: sqlx::Row::get(&row, "is_active"),
            priority: sqlx::Row::get(&row, "priority"),
        })
        .collect())
}

pub fn fallback_cluster_mirrors() -> Vec<ClusterMirrorRecord> {
    DEFAULT_CLUSTER_MIRRORS
        .iter()
        .enumerate()
        .map(|(idx, url)| ClusterMirrorRecord {
            url: (*url).to_string(),
            is_active: true,
            priority: idx as i32,
        })
        .collect()
}
