using System;
using Xunit;
using CncCollector.Config;

namespace CncCollector.Tests
{
    /// <summary>
    /// ConfigLoader 静态类测试（数据库连接部分通过异常处理实现，不抛出异常）
    /// </summary>
    public class ConfigLoaderTests
    {
        [Fact(DisplayName = "LoadRuntimeConfig_无效连接字符串_不抛异常")]
        public void LoadRuntimeConfig_无效连接字符串_不抛异常()
        {
            var cfg = new CollectorConfig();
            // 使用无效连接串，理论上应被内部 catch 捕获，不抛异常
            ConfigLoader.LoadRuntimeConfig("Server=invalid;Database=nosuchdb;User Id=x;Password=y;", cfg);
        }

        [Fact(DisplayName = "LoadRuntimeConfig_Null配置对象_不抛异常")]
        public void LoadRuntimeConfig_Null配置对象_不抛异常()
        {
            // 第二个参数为 null，方法内部需要处理空对象场景（不会抛出异常）
            ConfigLoader.LoadRuntimeConfig("Server=invalid;Database=nosuchdb;User Id=x;Password=y;", null);
        }

        [Fact(DisplayName = "LoadRuntimeConfig_默认配置对象_属性值不变")]
        public void LoadRuntimeConfig_默认配置对象_属性值不变()
        {
            var cfg = new CollectorConfig();
            ConfigLoader.LoadRuntimeConfig("Server=invalid;Database=nosuchdb;User Id=x;Password=y;", cfg);

            // 连接失败时应保持默认值
            Assert.Equal(5800, cfg.ApiPort);
            Assert.Equal("collector_api_key_2026", cfg.ApiKey);
            Assert.Equal(10, cfg.HeartbeatIntervalSeconds);
            Assert.Equal(30, cfg.ConfigPollIntervalSeconds);
            Assert.Equal("01:00", cfg.DailySummaryTime);
            Assert.Equal("CncCollector", cfg.ServiceId);
            Assert.Equal(3, cfg.CollectRetryCount);
            Assert.Equal(30, cfg.CollectRetryIntervalSeconds);
            Assert.Equal(5, cfg.CollectFailAlertThreshold);
        }

        [Fact(DisplayName = "LoadRuntimeConfig_各配置项映射正确")]
        public void LoadRuntimeConfig_各配置项映射正确()
        {
            // 设定一个初始对象的自定义值，模拟数据库连接失败时保持这些初始值
            var cfg = new CollectorConfig
            {
                ApiPort = 12345,
                ApiKey = "custom_key",
                HeartbeatIntervalSeconds = 99,
                ConfigPollIntervalSeconds = 77,
                DailySummaryTime = "04:44",
                ServiceId = "CustomSvc",
                CollectRetryCount = 7,
                CollectRetryIntervalSeconds = 11,
                CollectFailAlertThreshold = 9
            };

            ConfigLoader.LoadRuntimeConfig("Server=invalid;Database=nosuchdb;User Id=x;Password=y;", cfg);

            // 由于数据库连接失败，全部属性应保持初始值
            Assert.Equal(12345, cfg.ApiPort);
            Assert.Equal("custom_key", cfg.ApiKey);
            Assert.Equal(99, cfg.HeartbeatIntervalSeconds);
            Assert.Equal(77, cfg.ConfigPollIntervalSeconds);
            Assert.Equal("04:44", cfg.DailySummaryTime);
            Assert.Equal("CustomSvc", cfg.ServiceId);
            Assert.Equal(7, cfg.CollectRetryCount);
            Assert.Equal(11, cfg.CollectRetryIntervalSeconds);
            Assert.Equal(9, cfg.CollectFailAlertThreshold);
        }
    }
}
