using System;
using System.Linq;
using CncModels.Constants;
using CncModels.Dto;
using CncModels.Dto.Worker;
using CncService;
using CncService.Impl;
using Xunit;

namespace CncService.Tests
{
    /// <summary>
    /// WorkerService 员工管理测试
    /// 测试场景：CRUD、唯一性校验（工号）、绑定/解绑机床、参数校验
    /// </summary>
    [Collection("Database")]
    public class WorkerServiceTests : IDisposable
    {
        private readonly WorkerService _service;

        public WorkerServiceTests()
        {
            TestDb.TruncateAll();
            _service = ServiceFactory.CreateWorkerService();
        }

        public void Dispose()
        {
            TestDb.TruncateAll();
        }

        /// <summary>辅助方法：插入测试工人</summary>
        private int InsertTestWorker(string code = "W001", string name = "工人1")
        {
            return _service.Create(new CreateWorkerRequest
            {
                Code = code,
                Name = name
            });
        }

        /// <summary>辅助方法：插入测试机床</summary>
        private int InsertTestMachine(string deviceCode = "M001")
        {
            TestDb.Execute(@"INSERT INTO cnc_collect_address (name, url, brand_id, collect_interval, is_enabled, created_at, updated_at)
                VALUES ('测试地址', 'http://test', 1, 30, 1, NOW(), NOW())");
            TestDb.Execute(@"INSERT INTO cnc_machine (device_code, name, workshop_id, collect_address_id, ip_address, brand_id, is_enabled, created_at, updated_at)
                VALUES (@code, '测试机床', 1, 1, '0.0.0.0', 1, 1, NOW(), NOW())",
                new { code = deviceCode });
            return TestDb.QuerySingle<int>("SELECT MAX(id) FROM cnc_machine");
        }

        // ======== GetList ========

        [Fact]
        public void GetList_无数据_返回空列表()
        {
            var result = _service.GetList(new WorkerQuery { Page = 1, PageSize = 20 });
            Assert.NotNull(result);
            Assert.Equal(0, result.Total);
        }

        [Fact]
        public void GetList_有数据_返回分页结果()
        {
            InsertTestWorker("W001", "工人1");
            InsertTestWorker("W002", "工人2");

            var result = _service.GetList(new WorkerQuery { Page = 1, PageSize = 20 });
            Assert.Equal(2, result.Total);
        }

        [Fact]
        public void GetList_查询参数为null_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.GetList(null));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== GetById ========

        [Fact]
        public void GetById_存在的ID_返回工人详情()
        {
            var id = InsertTestWorker();
            var detail = _service.GetById(id);

            Assert.NotNull(detail);
            Assert.Equal("W001", detail.Code);
            Assert.Equal("工人1", detail.Name);
            Assert.True(detail.IsEnabled);
        }

        [Fact]
        public void GetById_带机床绑定_返回机床名称()
        {
            var workerId = InsertTestWorker();
            var machineId = InsertTestMachine();
            _service.BindMachine(workerId, machineId);

            var detail = _service.GetById(workerId);
            Assert.Equal(1, detail.MachineCount);
            Assert.Contains("测试机床", detail.MachineNames);
        }

        [Fact]
        public void GetById_不存在的ID_抛出NotFound异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.GetById(99999));
            Assert.Equal(ErrorCode.NotFound, ex.Code);
        }

        [Fact]
        public void GetById_无效ID_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.GetById(0));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== Create ========

        [Fact]
        public void Create_正常新增_返回自增ID()
        {
            var id = InsertTestWorker();
            Assert.True(id > 0);
        }

        [Fact]
        public void Create_请求为null_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Create(null));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        [Fact]
        public void Create_工号为空_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Create(new CreateWorkerRequest
            {
                Code = "",
                Name = "工人"
            }));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        [Fact]
        public void Create_工号为空格_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Create(new CreateWorkerRequest
            {
                Code = "   ",
                Name = "工人"
            }));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        [Fact]
        public void Create_重复工号_抛出Conflict异常()
        {
            InsertTestWorker("W001");
            var ex = Assert.Throws<BusinessException>(() => _service.Create(new CreateWorkerRequest
            {
                Code = "W001",
                Name = "工人2"
            }));
            Assert.Equal(ErrorCode.Conflict, ex.Code);
        }

        // ======== Update ========

        [Fact]
        public void Update_正常修改_返回true()
        {
            var id = InsertTestWorker();
            var result = _service.Update(id, new UpdateWorkerRequest { Name = "修改后工人" });
            Assert.True(result);

            var updated = _service.GetById(id);
            Assert.Equal("修改后工人", updated.Name);
        }

        [Fact]
        public void Update_不存在的ID_抛出NotFound异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Update(99999, new UpdateWorkerRequest { Name = "测试" }));
            Assert.Equal(ErrorCode.NotFound, ex.Code);
        }

        [Fact]
        public void Update_请求为null_抛出BadRequest异常()
        {
            var id = InsertTestWorker();
            var ex = Assert.Throws<BusinessException>(() => _service.Update(id, null));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        [Fact]
        public void Update_无效ID_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Update(0, new UpdateWorkerRequest { Name = "测试" }));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== Delete ========

        [Fact]
        public void Delete_存在的ID_返回true()
        {
            var id = InsertTestWorker();
            var result = _service.Delete(id);
            Assert.True(result);
        }

        [Fact]
        public void Delete_删除后查询不到()
        {
            var id = InsertTestWorker();
            _service.Delete(id);
            Assert.Throws<BusinessException>(() => _service.GetById(id));
        }

        [Fact]
        public void Delete_同时解绑机床()
        {
            var workerId = InsertTestWorker();
            var machineId = InsertTestMachine();
            _service.BindMachine(workerId, machineId);

            _service.Delete(workerId);

            var count = TestDb.QuerySingle<int>(
                "SELECT COUNT(*) FROM cnc_worker_machine WHERE worker_id = @workerId",
                new { workerId });
            Assert.Equal(0, count);
        }

        [Fact]
        public void Delete_无效ID_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.Delete(0));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== ToggleEnabled ========

        [Fact]
        public void ToggleEnabled_切换启用状态()
        {
            var id = InsertTestWorker();
            var before = _service.GetById(id);
            var beforeState = before.IsEnabled;

            _service.ToggleEnabled(id);

            var after = _service.GetById(id);
            Assert.NotEqual(beforeState, after.IsEnabled);
        }

        [Fact]
        public void ToggleEnabled_无效ID_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.ToggleEnabled(0));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== BindMachine ========

        [Fact]
        public void BindMachine_正常绑定_返回true()
        {
            var workerId = InsertTestWorker();
            var machineId = InsertTestMachine();

            var result = _service.BindMachine(workerId, machineId);
            Assert.True(result);
        }

        [Fact]
        public void BindMachine_机床已被其他工人绑定_抛出Conflict异常()
        {
            var worker1 = InsertTestWorker("W001", "工人1");
            var worker2 = InsertTestWorker("W002", "工人2");
            var machineId = InsertTestMachine();

            _service.BindMachine(worker1, machineId);
            var ex = Assert.Throws<BusinessException>(() => _service.BindMachine(worker2, machineId));
            Assert.Equal(ErrorCode.Conflict, ex.Code);
        }

        [Fact]
        public void BindMachine_无效参数_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.BindMachine(0, 1));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        [Fact]
        public void BindMachine_负数参数_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.BindMachine(-1, -1));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }

        // ======== UnbindMachine ========

        [Fact]
        public void UnbindMachine_正常解绑_返回true()
        {
            var workerId = InsertTestWorker();
            var machineId = InsertTestMachine();
            _service.BindMachine(workerId, machineId);

            var result = _service.UnbindMachine(workerId, machineId);
            Assert.True(result);
        }

        [Fact]
        public void UnbindMachine_无效参数_抛出BadRequest异常()
        {
            var ex = Assert.Throws<BusinessException>(() => _service.UnbindMachine(0, 1));
            Assert.Equal(ErrorCode.BadRequest, ex.Code);
        }
    }
}
