using System;
using System.Linq;
using CncModels.Entity;
using CncRepository.Impl;
using Xunit;

namespace CncRepository.Tests
{
    /// <summary>
    /// 品牌仓储测试
    /// </summary>
    [Collection("Database")]
    public class BrandRepositoryTests : IDisposable
    {
        private readonly BrandRepository _repo;

        public BrandRepositoryTests()
        {
            _repo = new BrandRepository(TestDb.ConnectionString);
            TestDb.TruncateAll();
        }

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

        [Fact]
        public void GetAll_返回所有品牌()
        {
            var result = _repo.GetAll();
            Assert.NotNull(result);
            Assert.True(result.Count >= 1);
            Assert.Equal("FANUC", result[0].BrandName);
        }

        [Fact]
        public void GetById_存在的ID_返回品牌()
        {
            var result = _repo.GetById(1);
            Assert.NotNull(result);
            Assert.Equal("FANUC", result.BrandName);
        }

        [Fact]
        public void Create_新增品牌_返回自增ID()
        {
            var entity = new Brand
            {
                BrandName = "Siemens",
                DeviceField = "device",
                TagsPath = "tags",
                IsEnabled = 1,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            var id = _repo.Create(entity);
            Assert.True(id > 0);
            Assert.Equal("Siemens", _repo.GetById(id).BrandName);
        }

        [Fact]
        public void Update_修改品牌_返回true()
        {
            var entity = _repo.GetById(1);
            entity.BrandName = "FANUC-修改";
            entity.UpdatedAt = DateTime.Now;
            var result = _repo.Update(entity);
            Assert.True(result);
        }

        [Fact]
        public void Delete_存在的ID_返回true()
        {
            var id = _repo.Create(new Brand
            {
                BrandName = "待删除", DeviceField = "d", TagsPath = "t", IsEnabled = 1,
                CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now
            });
            Assert.True(_repo.Delete(id));
        }

        [Fact]
        public void ToggleEnabled_切换启用状态()
        {
            var before = _repo.GetById(1).IsEnabled;
            _repo.ToggleEnabled(1);
            var after = _repo.GetById(1).IsEnabled;
            Assert.NotEqual(before, after);
        }

        [Fact]
        public void GetFieldMappingCount_返回字段映射数量()
        {
            var count = _repo.GetFieldMappingCount(1);
            Assert.True(count >= 0);
        }

        [Fact]
        public void GetCollectAddressCount_返回关联地址数量()
        {
            var count = _repo.GetCollectAddressCount(1);
            Assert.True(count >= 0);
        }
    }
}
