using Microsoft.Extensions.Caching.Memory;
using MongoDB.Driver;
using OnlyOneAccessTemplate.Models;

namespace OnlyOneAccessTemplate.Services
{
    public class ConfigurationService : IConfigurationService
    {
        private readonly IMongoDatabase _database;
        private readonly IMemoryCache _cache;

        public ConfigurationService(IMongoDatabase database, IMemoryCache cache)
        {
            _database = database;
            _cache = cache;
        }

        public async Task<SiteConfiguration> GetConfigurationAsync(string domain)
        {
            var cacheKey = $"config_{domain}";
            if (_cache.TryGetValue(cacheKey, out SiteConfiguration cachedConfig))
                return cachedConfig;

            var collection = _database.GetCollection<SiteConfiguration>("SiteConfigurations");
            var config = await collection.Find(x => x.Domain == domain).FirstOrDefaultAsync();

            if (config != null)
                _cache.Set(cacheKey, config, TimeSpan.FromMinutes(30));

            return config;
        }

        public async Task<List<ConverterConfig>> GetConvertersAsync(string language)
        {
            var collection = _database.GetCollection<ConverterConfig>("Converters");
            return await collection.Find(x => x.IsActive).ToListAsync();
        }

        public async Task<ConverterConfig> GetConverterAsync(string id, string language)
        {
            var collection = _database.GetCollection<ConverterConfig>("Converters");
            return await collection.Find(x => x.Id == id && x.IsActive).FirstOrDefaultAsync();
        }
    }
}
