//! Typed fetch helpers for Drift-specific Redis data.

use std::collections::HashMap;

use solana_pubkey::Pubkey;

use pyra_types::{Cache, DriftUser, SpotMarket};

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

impl RedisClient {
    /// Fetch a Drift user account by the vault (authority) address.
    pub async fn fetch_drift_user(&self, authority: &Pubkey) -> RedisResult<Option<DriftUser>> {
        let key = RedisKey::drift_user(authority);
        let cached: Option<Cache<DriftUser>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

    /// Fetch a single Drift spot market by index.
    pub async fn fetch_spot_market(&self, market_index: u16) -> RedisResult<Option<SpotMarket>> {
        let key = RedisKey::drift_spot_market(market_index);
        let cached: Option<Cache<SpotMarket>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

    /// Fetch multiple spot markets by their indices in a single MGET round-trip.
    ///
    /// Returns only the markets that were found and successfully deserialized.
    pub async fn fetch_spot_markets(
        &self,
        indices: &[u16],
    ) -> RedisResult<HashMap<u16, SpotMarket>> {
        if indices.is_empty() {
            return Ok(HashMap::new());
        }

        let keys: Vec<String> = indices
            .iter()
            .map(|&i| RedisKey::drift_spot_market(i).to_string())
            .collect();

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

        for (idx, val) in indices.iter().zip(values.into_iter()) {
            if let Some(raw) = val {
                if let Ok(cached) = serde_json::from_str::<Cache<SpotMarket>>(&raw) {
                    result.insert(*idx, cached.account);
                }
            }
        }

        Ok(result)
    }

    /// Fetch all spot markets by scanning `account:drift:spot_market:*` keys.
    ///
    /// Uses SCAN + MGET for efficiency. Returns market_index -> SpotMarket.
    pub async fn fetch_all_spot_markets(&self) -> RedisResult<HashMap<u16, SpotMarket>> {
        let pattern = RedisKey::pattern(RedisKey::DRIFT_SPOT_MARKET_PREFIX);
        let keys = self.scan_keys(&pattern).await?;

        if keys.is_empty() {
            return Ok(HashMap::new());
        }

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

        for val in values.into_iter().flatten() {
            if let Ok(cached) = serde_json::from_str::<Cache<SpotMarket>>(&val) {
                result.insert(cached.account.market_index, cached.account);
            }
        }

        Ok(result)
    }
}
