using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using DD.Persistence.Models;

namespace DD.Persistence.Repository.Repositories;
public class DataSourceSystemCachedRepository : DataSourceSystemRepository
{
    private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
    private readonly IMemoryCache memoryCache;
    private const int CacheExpirationInMinutes = 60;
    private readonly TimeSpan? AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);

    public DataSourceSystemCachedRepository(DbContext db, IMemoryCache memoryCache) : base(db)
    {
        this.memoryCache = memoryCache;
    }
    public override async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
    {
        await base.Add(dataSourceSystemDto, token);

        memoryCache.Remove(SystemCacheKey);
    }
    public override async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
    {
        var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) =>
        {
            cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;

            var dtos = await base.Get(token);

            return dtos;
        });

        return systems!;
    }
}