//! Typed fetch helpers for shared Redis data.
//!
//! These methods combine [`RedisKey`] patterns with JSON deserialization
//! to return strongly-typed Pyra account data from Redis.
//!
//! All account data is stored by the indexer wrapped in [`Cache<T>`],
//! which includes the Solana slot at which the data was last updated.
//! These helpers unwrap the `Cache` and return the inner account type.
//! If you need the slot information, use [`RedisClient::get_json::<Cache<T>>`] directly.

use std::collections::HashMap;

use pyra_tokens::AssetId;
use solana_pubkey::Pubkey;

use pyra_types::{Cache, SpendLimitsOrderAccount, Vault, WithdrawOrderAccount};

use crate::{RedisClient, RedisKey, RedisResult};

impl RedisClient {
    // ── Single-key fetches ────────────────────────────────────────────

    /// Fetch a Pyra vault account by its PDA address.
    pub async fn fetch_vault(&self, vault: &Pubkey) -> RedisResult<Option<Vault>> {
        let key = RedisKey::vault(vault);
        let cached: Option<Cache<Vault>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

    /// Fetch a withdraw order account by its PDA address.
    pub async fn fetch_withdraw_order(
        &self,
        order: &Pubkey,
    ) -> RedisResult<Option<WithdrawOrderAccount>> {
        let key = RedisKey::withdraw_order(order);
        let cached: Option<Cache<WithdrawOrderAccount>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

    /// Fetch a spend limits order account by its PDA address.
    pub async fn fetch_spend_limits_order(
        &self,
        order: &Pubkey,
    ) -> RedisResult<Option<SpendLimitsOrderAccount>> {
        let key = RedisKey::spend_limits_order(order);
        let cached: Option<Cache<SpendLimitsOrderAccount>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

    /// Fetch the oracle price for an asset (stored as a plain `f64` by the indexer).
    pub async fn fetch_price(&self, asset_id: AssetId) -> RedisResult<Option<f64>> {
        let key = RedisKey::price(asset_id);
        self.get_json(key.as_str()).await
    }

    // ── Batch fetches ─────────────────────────────────────────────────

    /// Fetch prices for multiple assets in a single MGET round-trip.
    ///
    /// Returns only assets that have a cached price.
    pub async fn fetch_prices(&self, asset_ids: &[AssetId]) -> RedisResult<HashMap<AssetId, f64>> {
        if asset_ids.is_empty() {
            return Ok(HashMap::new());
        }

        let keys: Vec<String> = asset_ids
            .iter()
            .map(|&id| RedisKey::price(id).to_string())
            .collect();

        let values = self.mget(&keys).await?;
        let mut result = HashMap::with_capacity(asset_ids.len());

        for (id, val) in asset_ids.iter().zip(values.into_iter()) {
            if let Some(raw) = val {
                if let Ok(price) = serde_json::from_str::<f64>(&raw) {
                    result.insert(*id, price);
                }
            }
        }

        Ok(result)
    }
}
