use config::AppConfig;
use deadpool_redis::cluster::{Connection, Manager, Pool};

#[derive(Clone)]
pub struct AppCache {
    pool: Pool,
    /// Single Redis URL for pub/sub (SUBSCRIBE needs a dedicated connection, can't use cluster).
    redis_url: String,
}

impl AppCache {
    pub async fn init(cfg: &AppConfig) -> anyhow::Result<Self> {
        let urls = cfg.redis_urls()?;
        let pool_size = cfg.redis_pool_size()?;
        let conn = Manager::new(urls.clone(), true)?;
        let pool = deadpool_redis::cluster::Pool::builder(conn)
            .max_size(pool_size as usize)
            .build()?;
        let redis_url = urls
            .first()
            .cloned()
            .unwrap_or_else(|| "redis://127.0.0.1:6379".to_string());

        Ok(Self { pool, redis_url })
    }
    pub async fn conn(&self) -> anyhow::Result<Connection> {
        Ok(self.pool.get().await?)
    }

    pub fn redis_pool(&self) -> &Pool {
        &self.pool
    }

    pub fn redis_url(&self) -> &str {
        &self.redis_url
    }
}
