using System.Threading.Tasks;
using BLL.Interfaces;
using Microsoft.Extensions.Caching.Memory;

namespace BLL.Services
{
    public class MemoryCacheService : ICacheService
    {
        private readonly IMemoryCache _cache;

        public MemoryCacheService(IMemoryCache cache)
        {
            _cache = cache;
        }

        public ValueTask<T> GetAsync<T>(string key)
        {
            if (_cache.TryGetValue(key, out T value))
            {
                return ValueTask.FromResult(value);
            }
            return ValueTask.FromResult(default(T));
        }

        public ValueTask SetAsync<T>(string key, T value, int expirationMinutes = 30)
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(System.TimeSpan.FromMinutes(expirationMinutes));

            _cache.Set(key, value, cacheEntryOptions);
            return ValueTask.CompletedTask;
        }

        public ValueTask RemoveAsync(string key)
        {
            _cache.Remove(key);
            return ValueTask.CompletedTask;
        }

        public ValueTask<bool> ExistsAsync(string key)
        {
            return ValueTask.FromResult(_cache.TryGetValue(key, out _));
        }
    }
}