use std::fmt;

#[derive(Debug)]
pub enum CacheError {
    Config(String),
    Protocol(String),
    Redis(redis::RedisError),
    Serialize(serde_json::Error),
    Timeout(&'static str),
}

impl fmt::Display for CacheError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Config(message) => {
                write!(formatter, "cache config error: {message}")
            }
            Self::Protocol(message) => {
                write!(formatter, "cache protocol error: {message}")
            }
            Self::Redis(error) => {
                write!(formatter, "redis cache error: {error}")
            }
            Self::Serialize(error) => {
                write!(formatter, "cache serialization error: {error}")
            }
            Self::Timeout(operation) => {
                write!(formatter, "cache operation timed out: {operation}")
            }
        }
    }
}

impl std::error::Error for CacheError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Redis(error) => Some(error),
            Self::Serialize(error) => Some(error),
            Self::Config(_) | Self::Protocol(_) | Self::Timeout(_) => None,
        }
    }
}

pub type CacheResult<T> = Result<T, CacheError>;
