use crate::{config, support::drivers, traits::CacheDriver, Cache, CacheResult};
use soph_config::support::config;

impl Cache {
    pub fn new() -> CacheResult<Self> {
        let config = config().parse::<config::Cache>()?;

        let driver = match config.driver {
            config::Driver::Null => drivers::null::new(),
            #[cfg(feature = "memory")]
            config::Driver::Memory => drivers::mem::new(),
        };

        Ok(Self { driver })
    }

    pub async fn has(&self, key: &str) -> CacheResult<bool> {
        self.driver.has(key).await
    }

    pub async fn get(&self, key: &str) -> CacheResult<Option<String>> {
        self.driver.get(key).await
    }

    pub async fn insert(&self, key: &str, value: &str) -> CacheResult<()> {
        self.driver.insert(key, value).await
    }

    pub async fn remove(&self, key: &str) -> CacheResult<()> {
        self.driver.remove(key).await
    }

    pub async fn clear(&self) -> CacheResult<()> {
        self.driver.clear().await
    }
}

impl std::ops::Deref for Cache {
    type Target = Box<dyn CacheDriver>;

    fn deref(&self) -> &Self::Target {
        &self.driver
    }
}
