use crate::{async_trait, traits::CacheDriver, CacheResult};
use std::sync::Arc;

pub fn new() -> Box<dyn CacheDriver> {
    let cache = moka::future::Cache::builder().max_capacity(32 * 1024 * 1024).build();

    Box::new(Mem::new(cache))
}

pub struct Mem {
    inner: moka::future::Cache<String, String>,
}

impl Mem {
    pub fn new(inner: moka::future::Cache<String, String>) -> Self {
        Self { inner }
    }
}

#[async_trait]
impl CacheDriver for Mem {
    async fn has(&self, key: &str) -> CacheResult<bool> {
        Ok(self.inner.contains_key(key))
    }

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

    async fn insert(&self, key: &str, value: &str) -> CacheResult<()> {
        self.inner.insert(key.to_string(), Arc::new(value).to_string()).await;

        Ok(())
    }

    async fn remove(&self, key: &str) -> CacheResult<()> {
        self.inner.remove(key).await;

        Ok(())
    }

    async fn clear(&self) -> CacheResult<()> {
        self.inner.invalidate_all();

        Ok(())
    }
}
