use cached::proc_macro::cached;
use pyth_lazer_protocol::jrpc::SymbolMetadata;
use std::time::Duration;
use url::Url;

/// Fetch metadata from the given URL and cache the result for 60 seconds.
/// The cache is shared across all calls to this function.
#[allow(
    clippy::unused_unit,
    reason = "unit cache key generated by cached macro"
)]
#[cached(
    time = 60,
    result = true,
    sync_writes = "default",
    key = "()",
    convert = "{ () }"
)]
pub async fn fetch_metadata(url: &Url) -> anyhow::Result<Vec<SymbolMetadata>> {
    let result = reqwest::get(url.clone()).await?;
    if result.status().is_success() {
        Ok(serde_json::from_str::<Vec<SymbolMetadata>>(
            &result.text().await?,
        )?)
    } else {
        anyhow::bail!(
            "Error getting metadata (status_code={}, body={})",
            result.status(),
            result.text().await.unwrap_or("none".to_string())
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    #[ignore]
    async fn test_fetch_metadata() {
        let url: Url = "https://history.pyth-lazer.dourolabs.app/history/v1/symbols"
            .parse()
            .expect("should never fail on valid hardcoded URL");
        println!("{:?}", fetch_metadata(&url).await.unwrap());
    }
}
