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

namespace CncRepository.Tests
{
    /// <summary>
    /// 系统配置仓储测试
    /// </summary>
    [Collection("Database")]
    public class SysConfigRepositoryTests : IDisposable
    {
        private readonly SysConfigRepository _repo;

        public SysConfigRepositoryTests()
        {
            _repo = new SysConfigRepository(TestDb.ConnectionString);
            TestDb.TruncateAll();
            // TruncateAll已插入admin_username/admin_password_hash，这里只需加test_key
            TestDb.Execute(@"INSERT IGNORE INTO cnc_sys_config (config_key, config_value, value_type, description, updated_at)
                VALUES ('test_key', 'test_value', 'string', '测试配置', NOW())");
        }

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

        [Fact]
        public void GetByKey_存在的Key_返回配置()
        {
            var result = _repo.GetByKey("test_key");
            Assert.NotNull(result);
            Assert.Equal("test_value", result.ConfigValue);
        }

        [Fact]
        public void GetByKey_不存在的Key_返回null()
        {
            var result = _repo.GetByKey("nonexistent_key");
            Assert.Null(result);
        }

        [Fact]
        public void GetAll_返回所有配置()
        {
            var result = _repo.GetAll();
            Assert.NotNull(result);
            Assert.True(result.Count >= 2);
        }

        [Fact]
        public void UpdateValue_修改配置值_返回true()
        {
            var cfg = _repo.GetByKey("test_key");
            var result = _repo.UpdateValue(cfg.Id, "new_value");
            Assert.True(result);
            Assert.Equal("new_value", _repo.GetByKey("test_key").ConfigValue);
        }
    }
}
