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

use crate::RedisKey;

impl RedisKey {
    // ── Drift-specific prefixes ──────────────────────────────────────

    pub const DRIFT_USER_PREFIX: &'static str = "account:drift:user";
    pub const DRIFT_USER_BY_PUBKEY_PREFIX: &'static str = "reverse:drift_user_pubkey";
    pub const DRIFT_SPOT_MARKET_PREFIX: &'static str = "account:drift:spot_market";

    // ── Drift-specific keys ──────────────────────────────────────────

    pub fn drift_user(authority: &Pubkey) -> Self {
        let p = Self::DRIFT_USER_PREFIX;
        Self::from_string(format!("{p}:{authority}"))
    }

    /// Reverse mapping: DriftUser account pubkey → authority (vault pubkey).
    pub fn drift_user_by_pubkey(pubkey: &Pubkey) -> Self {
        let p = Self::DRIFT_USER_BY_PUBKEY_PREFIX;
        Self::from_string(format!("{p}:{pubkey}"))
    }

    pub fn drift_spot_market(asset_id: AssetId) -> Self {
        let p = Self::DRIFT_SPOT_MARKET_PREFIX;
        Self::from_string(format!("{p}:{asset_id}"))
    }
}

#[cfg(test)]
#[allow(
    clippy::allow_attributes,
    clippy::allow_attributes_without_reason,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::arithmetic_side_effects,
    reason = "test code"
)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn drift_user_key_format() {
        let pk = Pubkey::from_str("11111111111111111111111111111111").unwrap();
        let key = RedisKey::drift_user(&pk);
        assert_eq!(
            key.to_string(),
            "account:drift:user:11111111111111111111111111111111"
        );
    }

    #[test]
    fn drift_spot_market_key_format() {
        let key = RedisKey::drift_spot_market(AssetId::USDC);
        assert_eq!(key.to_string(), "account:drift:spot_market:0");
    }

    #[test]
    fn drift_user_by_pubkey_key_format() {
        let pk = Pubkey::from_str("11111111111111111111111111111111").unwrap();
        let key = RedisKey::drift_user_by_pubkey(&pk);
        assert_eq!(
            key.to_string(),
            "reverse:drift_user_pubkey:11111111111111111111111111111111"
        );
    }
}
