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

namespace IWS5.Services.ImporterService;

public class DocumentFieldService : IDocumentFieldService
{
    private readonly IDocumentFieldRepository _repository;
    private readonly IMemoryCache _cache;
    private readonly ILogger _logService;
    private readonly TimeSpan _cacheExpiration = TimeSpan.FromHours(3);

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

    public async Task<Dictionary<int, List<DocumentFieldDto>>> GetValidDocumentFieldsAsync()
    {
        return await _cache.GetOrCreateAsync("DocumentFields", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = _cacheExpiration;
            var documentFields = await _repository.GetDocumentFieldsAsync();
            using (LogContext.PushProperty("LogContext", nameof(DocumentFieldService)))
                _logService.Information($"Cached {documentFields.Count} document fields.");
            return documentFields;
        }) ?? new();
    }
}
