use std::collections::HashMap;

use serde::Deserialize;

use crate::error::ApiError;
use super::InstrumentPair;

#[derive(Deserialize)]
struct KrakenResponse {
    result: HashMap<String, AssetPair>,
}

#[derive(Deserialize)]
struct AssetPair {
    wsname: Option<String>,
}

pub async fn fetch(client: &reqwest::Client) -> Result<Vec<InstrumentPair>, ApiError> {
    let resp: KrakenResponse = client
        .get("https://api.kraken.com/0/public/AssetPairs")
        .send()
        .await
        .map_err(|e| ApiError::Internal(format!("kraken request failed: {e}")))?
        .json()
        .await
        .map_err(|e| ApiError::Internal(format!("kraken json parse failed: {e}")))?;

    let pairs = resp
        .result
        .into_values()
        .filter_map(|ap| {
            let wsname = ap.wsname?;
            let (base, quote) = wsname.split_once('/')?;
            Some(InstrumentPair {
                base: base.to_owned(),
                quote: quote.to_owned(),
            })
        })
        .collect();

    Ok(pairs)
}
