using JSMR.Application.Common.Caching;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;
using System.Text.Json;

namespace JSMR.Infrastructure.Caching.Adapters;

public class DistributedCacheAdapter(IDistributedCache distributedCache) : ICache
{
    public async ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
    {
        byte[]? bytes = await distributedCache.GetAsync(key, cancellationToken);

        if (bytes == null)
            return default;

        string json = Encoding.UTF8.GetString(bytes);

        return JsonSerializer.Deserialize<T>(json);
    }

    public async ValueTask SetAsync<T>(string key, T value, CacheEntryOptions options, CancellationToken cancellationToken = default)
    {
        string json = JsonSerializer.Serialize(value);
        byte[] bytes = Encoding.UTF8.GetBytes(json);

        DistributedCacheEntryOptions distributedCacheOptions = new();

        if (options.AbsoluteExpirationRelativeToNow != null)
            distributedCacheOptions.SetAbsoluteExpiration(options.AbsoluteExpirationRelativeToNow.Value);

        if (options.AbsoluteExpiration != null)
            distributedCacheOptions.SetAbsoluteExpiration(options.AbsoluteExpiration.Value);

        if (options.SlidingExpiration != null)
            distributedCacheOptions.SetSlidingExpiration(options.SlidingExpiration.Value);

        await distributedCache.SetAsync(key, bytes, distributedCacheOptions, cancellationToken);
    }
}