using System;
using CncModels.Dto;
using CncModels.Dto.Log;
using CncModels.Entity;
using CncWebApi.Controllers;
using Xunit;

namespace CncWebApi.Tests
{
    /// <summary>
    /// LogController单元测试
    /// 系统日志 + 产量修正日志
    /// </summary>
    [Collection("Database")]
    public class LogControllerTests
    {
        private readonly LogController _controller;

        public LogControllerTests()
        {
            TestDb.TruncateAll();
            _controller = ControllerFactory.CreateLogController();
        }

        #region GetSystemLog - 系统日志

        /// <summary>
        /// 测试：空数据库返回空列表
        /// </summary>
        [Fact]
        public void GetSystemLog_EmptyDb_ShouldReturnEmpty()
        {
            var result = _controller.GetSystemLog(new SystemLogQuery());
            var response = ControllerFactory.Extract<PagedResult<SystemLogListItem>>(result);
            ControllerFactory.AssertSuccess(response);
            Assert.Empty(response.Data.Items);
        }

        /// <summary>
        /// 测试：有日志数据时返回列表
        /// </summary>
        [Fact]
        public void GetSystemLog_WithData_ShouldReturnItems()
        {
            TestDb.Execute(@"INSERT INTO log_system (log_level, source, message, created_at)
                VALUES ('INFO', '测试模块', '测试内容', NOW())");

            var result = _controller.GetSystemLog(new SystemLogQuery());
            var response = ControllerFactory.Extract<PagedResult<SystemLogListItem>>(result);
            Assert.NotEmpty(response.Data.Items);
        }

        #endregion

        #region GetAdjustmentLog - 产量修正日志

        /// <summary>
        /// 测试：空数据库返回空列表
        /// </summary>
        [Fact]
        public void GetAdjustmentLog_EmptyDb_ShouldReturnEmpty()
        {
            var result = _controller.GetAdjustmentLog(null, null, null, null, 1, 20);
            var response = ControllerFactory.Extract<PagedResult<ProductionAdjustment>>(result);
            ControllerFactory.AssertSuccess(response);
            Assert.Empty(response.Data.Items);
        }

        /// <summary>
        /// 测试：有修正日志时返回列表
        /// </summary>
        [Fact]
        public void GetAdjustmentLog_WithData_ShouldReturnItems()
        {
            TestDb.Execute(@"INSERT INTO cnc_production_adjustment (target_table, target_id, field_name, old_value, new_value, reason, created_at)
                VALUES ('cnc_daily_production', 1, 'total_quantity', 100, 200, '测试修正', NOW())");

            var result = _controller.GetAdjustmentLog(null, null, null, null, 1, 20);
            var response = ControllerFactory.Extract<PagedResult<ProductionAdjustment>>(result);
            Assert.NotEmpty(response.Data.Items);
        }

        #endregion
    }
}
