using Lada.Framework.Data.Domains;
using Lada.Framework.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;

namespace Ladaer.BackEnd.Infrastructures.Services
{
    public interface IAppConfigService
    {
        Task<string> GetConfigValueAsync(string key);
        Task LoadConfigsToCacheAsync();
    }


    public class AppConfigService : IAppConfigService
    {
        private readonly IRepository<AppConfig> _appConfigRepository;
        private readonly IMemoryCache _memoryCache;
        private readonly string _cacheKeyPrefix = "AppConfig_";



        public AppConfigService(IRepository<AppConfig> appConfigRepository, IMemoryCache memoryCache)
        {
            _appConfigRepository = appConfigRepository;
            _memoryCache = memoryCache;
        }
        

        public async Task<string> GetConfigValueAsync(string key)
        {
            if (!_memoryCache.TryGetValue($"{_cacheKeyPrefix}{key}", out string value))
            {
                var config = await _appConfigRepository.Query().FirstOrDefaultAsync(c=>c.Key == key);
                if (config != null)
                {
                    value = config.Value;
                    _memoryCache.Set($"{_cacheKeyPrefix}{key}", value, TimeSpan.FromHours(1));
                }
            }
            return value;
        }

        public async Task LoadConfigsToCacheAsync()
        {
            var configs = await _appConfigRepository.Query().ToListAsync();
            foreach (var config in configs)
            {
                _memoryCache.Set($"{_cacheKeyPrefix}{config.Key}", config.Value, TimeSpan.FromHours(1));
            }
        }
    }
}
