using System.Web.Http;
using System.Web.Http.Results;
using CncModels.Dto;
using CncRepository.Impl;
using CncRepository.Impl.Dashboard;
using CncRepository.Impl.Log;
using CncRepository.Interface;
using CncService.Impl;
using CncService.Interface;
using CncWebApi.Controllers;
using Xunit;

namespace CncWebApi.Tests
{
    /// <summary>
    /// Controller工厂 —— 创建Controller实例用于单元测试
    /// 直接实例化Controller，不经过HTTP管线（跳过JwtAuthFilter等过滤器）
    /// 所有Repository/Service使用cnc_test真实数据库
    /// </summary>
    public static class ControllerFactory
    {
        private static readonly string _conn = TestDb.ConnectionString;
        private const string _jwtSecret = "test-jwt-secret-key-for-unit-testing-2024";

        #region Repository 创建

        private static ISysConfigRepository SysConfigRepo() => new SysConfigRepository(_conn);
        private static IBrandRepository BrandRepo() => new BrandRepository(_conn);
        private static IBrandFieldMappingRepository BrandFieldMappingRepo() => new BrandFieldMappingRepository(_conn);
        private static ICollectAddressRepository CollectAddressRepo() => new CollectAddressRepository(_conn);
        private static IMachineRepository MachineRepo() => new MachineRepository(_conn);
        private static IWorkerRepository WorkerRepo() => new WorkerRepository(_conn);
        private static IWorkerMachineRepository WorkerMachineRepo() => new WorkerMachineRepository(_conn);
        private static IWorkshopRepository WorkshopRepo() => new WorkshopRepository(_conn);
        private static IAlertRepository AlertRepo() => new AlertRepository(_conn);
        private static IDailyProductionRepository DailyProductionRepo() => new DailyProductionRepository(_conn);
        private static IProductionSegmentRepository ProductionSegmentRepo() => new ProductionSegmentRepository(_conn);
        private static IProductionAdjustmentRepository ProductionAdjustmentRepo() => new ProductionAdjustmentRepository(_conn);
        private static IScreenConfigRepository ScreenConfigRepo() => new ScreenConfigRepository(_conn);
        private static IScreenFilterRepository ScreenFilterRepo() => new ScreenFilterRepository(_conn);
        private static IDashboardRepository DashboardRepo() => new DashboardRepository(_conn);
        private static ICollectorHeartbeatRepository HeartbeatRepo() => new CollectorHeartbeatRepository(_conn);
        private static ISystemLogRepository SystemLogRepo() => new SystemLogRepository(_conn);
        private static ICollectRawRepository CollectRawRepo() => new CncRepository.Impl.Log.CollectRawRepository(_conn);

        #endregion

        #region Service 创建

        private static IAuthService CreateAuthService() => new AuthService(SysConfigRepo(), _jwtSecret);
        private static IDashboardService CreateDashboardService() => new DashboardService(DashboardRepo(), HeartbeatRepo(), SysConfigRepo());
        private static IMachineService CreateMachineService() => new MachineService(MachineRepo(), CollectAddressRepo(), WorkerMachineRepo(), BrandRepo());
        private static IBrandService CreateBrandService() => new BrandService(BrandRepo(), BrandFieldMappingRepo(), CollectAddressRepo());
        private static ICollectAddressService CreateCollectAddressService() => new CollectAddressService(CollectAddressRepo(), MachineRepo(), BrandRepo(), WorkshopRepo(), CollectRawRepo(), SysConfigRepo());
        private static IWorkerService CreateWorkerService() => new WorkerService(WorkerRepo(), WorkerMachineRepo(), MachineRepo(), SysConfigRepo());
        private static IProductionService CreateProductionService() => new ProductionService(DailyProductionRepo(), ProductionSegmentRepo(), ProductionAdjustmentRepo());
        private static IAlertService CreateAlertService() => new AlertService(AlertRepo());
        private static IWorkshopService CreateWorkshopService() => new WorkshopService(WorkshopRepo());
        private static IScreenService CreateScreenService() => new ScreenService(ScreenConfigRepo(), ScreenFilterRepo(), WorkshopRepo());
        private static ISystemLogService CreateSystemLogService() => new SystemLogService(SystemLogRepo());

        #endregion

        #region Controller 创建

        /// <summary>创建AuthController（无JWT过滤）</summary>
        public static AuthController CreateAuthController() => new AuthController(CreateAuthService());

        /// <summary>创建HealthController（无依赖）</summary>
        public static HealthController CreateHealthController() => new HealthController();

        /// <summary>创建BrandController</summary>
        public static BrandController CreateBrandController() => new BrandController(CreateBrandService());

        /// <summary>创建MachineController</summary>
        public static MachineController CreateMachineController() => new MachineController(CreateMachineService());

        /// <summary>创建CollectAddressController</summary>
        public static CollectAddressController CreateCollectAddressController() => new CollectAddressController(CreateCollectAddressService());

        /// <summary>创建WorkerController</summary>
        public static WorkerController CreateWorkerController() => new WorkerController(CreateWorkerService());

        /// <summary>创建DashboardController</summary>
        public static DashboardController CreateDashboardController() => new DashboardController(CreateDashboardService(), SysConfigRepo());

        /// <summary>创建SettingsController（系统配置+车间管理）</summary>
        public static SettingsController CreateSettingsController() => new SettingsController(SysConfigRepo(), CreateWorkshopService());

        /// <summary>创建ProductionController</summary>
        public static ProductionController CreateProductionController() => new ProductionController(CreateProductionService());

        /// <summary>创建AlertController</summary>
        public static AlertController CreateAlertController() => new AlertController(CreateAlertService());

        /// <summary>创建LogController</summary>
        public static LogController CreateLogController() => new LogController(CreateSystemLogService(), ProductionAdjustmentRepo());

        /// <summary>创建ScreenConfigController</summary>
        public static ScreenConfigController CreateScreenConfigController() => new ScreenConfigController(CreateScreenService());

        /// <summary>创建ScreenController（大屏，无JWT过滤）</summary>
        public static ScreenController CreateScreenController() => new ScreenController(CreateDashboardService(), CreateScreenService(), SysConfigRepo());

        /// <summary>创建OptionController</summary>
        public static OptionController CreateOptionController() => new OptionController(
            CreateWorkshopService(), CreateBrandService(), CreateMachineService(),
            CreateWorkerService(), CreateCollectAddressService());

        #endregion

        #region 测试辅助方法

        /// <summary>
        /// 从IHttpActionResult中提取ApiResponse&lt;T&gt;内容
        /// Controller返回Ok(ApiResponse&lt;T&gt;.Success(data))，实际类型是OkNegotiatedContentResult&lt;ApiResponse&lt;T&gt;&gt;
        /// </summary>
        public static ApiResponse<T> Extract<T>(IHttpActionResult result)
        {
            var okResult = result as OkNegotiatedContentResult<ApiResponse<T>>;
            Assert.NotNull(okResult);
            return okResult.Content;
        }

        /// <summary>
        /// 验证ApiResponse成功：Code=0, Message="success"
        /// </summary>
        public static void AssertSuccess<T>(ApiResponse<T> response)
        {
            Assert.Equal(0, response.Code);
            Assert.Equal("success", response.Message);
        }

        #endregion
    }
}
