use anyhow::Result;
use athena_rs::client::AthenaClient;
use serde_json::json;
use std::sync::Arc;

pub struct Provider {
    pub client: Arc<AthenaClient>,
}

impl Provider {
    pub async fn new() -> Option<Self> {
        let url: String = std::env::var("ATHENA_URL").ok()?;
        let key: String = std::env::var("ATHENA_API_KEY").ok()?;
        match AthenaClient::new(url, key, "dexter").await {
            Ok(client) => Some(Self {
                client: Arc::new(client),
            }),
            Err(e) => {
                tracing::warn!("Failed to init Athena client: {}", e);
                None
            }
        }
    }

    pub async fn add_url_to_registry(&self, url: &str, config_name: &str) -> Result<()> {
        add_url_to_registry(&self.client, url, config_name).await
    }
}

pub async fn add_url_to_registry(
    client: &AthenaClient,
    url: &str,
    config_name: &str,
) -> Result<()> {
    let payload = json!({
        "url": url,
        "config_name": config_name,
    });
    client
        .insert("url_registry")
        .payload(payload)
        .execute()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to insert URL: {}", e))?;
    Ok(())
}

pub async fn check_url_in_registry_db(client: &AthenaClient, url: &str) -> Result<bool> {
    let result = client
        .fetch("url_registry")
        .where_eq("url", url)
        .execute()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to check URL: {}", e))?;
    Ok(!result.rows.is_empty())
}
