use crate::AppConfig;

impl AppConfig {
    pub fn redis_url(&self) -> anyhow::Result<String> {
        let urls = self.redis_urls()?;
        urls.into_iter().next().ok_or_else(|| {
            anyhow::anyhow!("APP_REDIS_URLS or APP_REDIS_URL is empty")
        })
    }

    pub fn redis_urls(&self) -> anyhow::Result<Vec<String>> {
        if let Some(urls) = self.env.get("APP_REDIS_URLS") {
            return Ok(urls.split(',').map(|s| s.trim().to_string()).collect());
        }
        if let Some(url) = self.env.get("APP_REDIS_URL") {
            return Ok(vec![url.to_string()]);
        }
        Err(anyhow::anyhow!("APP_REDIS_URLS or APP_REDIS_URL not found"))
    }

    pub fn redis_pool_size(&self) -> anyhow::Result<u32> {
        if let Some(pool_size) = self.env.get("APP_REDIS_POOL_SIZE") {
            return Ok(pool_size.parse::<u32>()?);
        }
        Ok(10)
    }

    pub fn redis_connect_timeout(&self) -> anyhow::Result<u64> {
        if let Some(timeout) = self.env.get("APP_REDIS_CONNECT_TIMEOUT") {
            return Ok(timeout.parse::<u64>()?);
        }
        Ok(5)
    }

    pub fn redis_acquire_timeout(&self) -> anyhow::Result<u64> {
        if let Some(timeout) = self.env.get("APP_REDIS_ACQUIRE_TIMEOUT") {
            return Ok(timeout.parse::<u64>()?);
        }
        Ok(5)
    }
}
