using Common.Global;
using Database.Database;
using Microsoft.Identity.Client;

namespace Esim.Apis.Singleton
{
    public class ConfigManager
    {

        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ConfigManager));

        private ModelContext dbContext;
        private List<Config> appConfigs = new List<Config>();

        private ConfigManager()
        {
            dbContext = new DbHelper().GetDbContext(GlobalConfig.Configuration!);
            log.Debug("ConfigManager initialized");
        }

        private static readonly object lockObj = new object();

        private static ConfigManager? instance;
        public static ConfigManager Instance => instance ??= new ConfigManager();

        public void Initialize()
        {
            appConfigs = dbContext.Configs.ToList();
            log.Debug("ConfigManager initialized");
        }

        public string GetConfigWebValue(string configName, string lang = "lo")
        {
            var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "WEB");
            if (config != null)
            {
                log.Debug($"Config found: {configName} = {config.ValueLocal}");
                return GetValueByLang(config, lang);
            }
            log.Warn($"Config not found: {configName}");
            return string.Empty;
        }

        public string GetConfigSmsValue(string configName, string lang = "lo")
        {
            var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "SMS");
            if (config != null)
            {
                log.Debug($"Config found: {configName} = {config.ValueLocal}");
                return GetValueByLang(config, lang);
            }
            log.Warn($"Config not found: {configName}");
            return string.Empty;
        }

        public string GetConfigAppValue(string configName, string lang = "lo")
        {
            var config = appConfigs.FirstOrDefault(c => c.Name == configName && c.Type == "APP");
            if (config != null)
            {
                log.Debug($"Config found: {configName} = {config.ValueLocal}");
                return GetValueByLang(config, lang);
            }
            log.Warn($"Config not found: {configName}");
            return string.Empty;
        }

        /// <summary>
        /// Get config value by language: vi=Vietnamese, en=English, lo=Lao (default)
        /// </summary>
        private string GetValueByLang(Config config, string lang)
        {
            return lang switch
            {
                "vi" => config.Value ?? config.ValueLocal ?? "",
                "en" => config.ValueGlobal ?? config.ValueLocal ?? "",
                _ => config.ValueLocal ?? ""  // Default: Lao
            };
        }

        // loop 5p to refresh
        public void RefreshConfigs()
        {
            while (true)
            {
                try
                {
                    log.Debug($"ConfigManager refreshing...");
                    appConfigs = dbContext.Configs.ToList();
                    log.Debug("ConfigManager refreshed");
                }
                catch (Exception ex)
                {
                    log.Error("Error refreshing configs", ex);
                }
                Thread.Sleep(5 * 60 * 1000); // 5 minutes
            }
        }
    }
}
