using System;
using System.Collections.Generic;
using Xunit;
using CncCollector.Core;
using CncCollector.Config;

namespace CncCollector.Tests
{
    /// <summary>
    /// 测试 CncCollector.Core.CollectorEngine 类的基础行为。
    /// 由于直接连接数据库，测试时使用无效连接字符串以触发错误处理路径
    /// </summary>
    public class CollectorEngineTests
    {
        private CollectorConfig CreateInvalidConfig()
        {
            return new CollectorConfig
            {
                BusinessConnection = "Server=invalid;Database=invalid;User Id=invalid;Password=invalid;",
                LogConnection = "Server=invalid;Database=invalid;User Id=invalid;Password=invalid;",
                ApiPort = 5800
            };
        }

        [Fact]
        public void 构造函数_正常创建()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            Assert.False(engine.IsRunning);
            Assert.Equal(0, engine.WorkerCount);
        }

        [Fact]
        public void IsRunning_初始值_false()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            Assert.False(engine.IsRunning);
        }

        [Fact]
        public void GetStatus_未启动_返回停止状态()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            var status = engine.GetStatus();
            Assert.NotNull(status);
            Assert.True(status.ContainsKey("isRunning"));
            Assert.True(status.ContainsKey("startTime"));
            Assert.True(status.ContainsKey("uptimeSeconds"));
            Assert.True(status.ContainsKey("workerCount"));
            Assert.True(status.ContainsKey("workers"));
        }

        [Fact]
        public void Start_无DB连接_不崩溃()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            // 应该不会抛出异常，即使数据库连接失败
            engine.Start();

            // 启动后应该进入运行态（实现可能会因为加载地址失败而没有工作地址，但不会崩溃）
            Assert.True(engine.IsRunning);
        }

        [Fact]
        public void Stop_未启动_不崩溃()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            // 未启动调用 Stop 不应抛出异常
            engine.Stop();
        }

        [Fact]
        public void Refresh_未启动_不崩溃()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            // 未启动时刷新应当不抛出异常
            engine.Refresh();
        }

        [Fact]
        public void UptimeSeconds_未启动_返回0()
        {
            var config = CreateInvalidConfig();
            var engine = new CollectorEngine(config);

            Assert.Equal(0, engine.UptimeSeconds);
        }
    }
}
