using IWS5.DatabaseAccess.Interfaces.Importer;
using IWS5.Importer.Abstractions.DTO;
using IWS5.Importer.Abstractions.Services;
using Microsoft.Extensions.Caching.Memory;
using Serilog;

namespace IWS5.Services.ImporterService;

public class FolderFieldService : IFolderFieldService
{
    private readonly IFolderFieldRepository _repository;
    private readonly IMemoryCache _cache;
    private readonly ILogger _logService;
    private readonly TimeSpan _cacheExpiration = TimeSpan.FromHours(3);

    public FolderFieldService(IFolderFieldRepository repository, ILogger logService, IMemoryCache cache)
    {
        _repository = repository;
        _logService = logService;
        _cache = cache;
    }

    public async Task<Dictionary<int, List<FolderFieldDto>>> GetValidFolderFieldsAsync()
    {
        return await _cache.GetOrCreateAsync("FolderFields", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = _cacheExpiration;
            var folderFields = await _repository.GetFolderFieldsAsync();
            _logService.Information($"Cached {folderFields.Count} folder fields.");
            return folderFields;
        }) ?? new();
    }
}
