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

namespace IWS5.Services.ImporterService;

public class DocumentCabinetService(ILogger logService, IMemoryCache cache, IDocumentCabinetRepository cabinetRepository) : IDocumentCabinetService
{
    private readonly TimeSpan _cacheExpiration = TimeSpan.FromHours(3);
    public async Task<Dictionary<string, int>> GetCabinetDataAsync()
    {
        return await cache.GetOrCreateAsync("CabinetData", async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = _cacheExpiration;
            var cabinetData = await cabinetRepository.GetCabinetDataAsync();
            using (LogContext.PushProperty("LogContext", nameof(DocumentCabinetService)))
                logService.Information($"Cached {cabinetData.Count} document cabinets.");
            return cabinetData;
        }) ?? new();
    }

    public async Task<int> GetCabinetIdByNameAsync(string? cabinetName)
    {
        var cabinetData = await GetCabinetDataAsync();
        return cabinetData.TryGetValue(cabinetName, out var cabinetId) ? cabinetId : 1;
    }
}
