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

use std::collections::HashMap;

use pyra_tokens::AssetId;
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 asset ID.
    pub async fn fetch_spot_market(&self, asset_id: AssetId) -> RedisResult<Option<SpotMarket>> {
        let key = RedisKey::drift_spot_market(asset_id);
        let cached: Option<Cache<SpotMarket>> = self.get_json(key.as_str()).await?;
        Ok(cached.map(|c| c.account))
    }

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

        let keys: Vec<String> = asset_ids
            .iter()
            .map(|&id| RedisKey::drift_spot_market(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(cached) = serde_json::from_str::<Cache<SpotMarket>>(&raw) {
                    result.insert(*id, cached.account);
                }
            }
        }

        Ok(result)
    }

    /// Fetch all spot markets by scanning `account:drift:spot_market:*` keys.
    ///
    /// Uses SCAN + MGET for efficiency. Returns asset_id -> SpotMarket.
    /// Only includes tokens known to pyra-tokens.
    pub async fn fetch_all_spot_markets(&self) -> RedisResult<HashMap<AssetId, 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 prefix_with_colon = format!("{}:", RedisKey::DRIFT_SPOT_MARKET_PREFIX);
        let values = self.mget(&keys).await?;
        let mut result = HashMap::with_capacity(keys.len());

        for (key, val) in keys.iter().zip(values.into_iter()) {
            let Some(raw) = val else { continue };
            let Some(suffix) = key.strip_prefix(prefix_with_colon.as_str()) else {
                continue;
            };
            let Ok(id_raw) = suffix.parse::<u16>() else {
                continue;
            };
            let Ok(asset_id) = AssetId::new(id_raw) else {
                continue;
            };
            if let Ok(cached) = serde_json::from_str::<Cache<SpotMarket>>(&raw) {
                result.insert(asset_id, cached.account);
            }
        }

        Ok(result)
    }
}
