using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using CncModels.Dto;
using CncModels.Dto.Settings;
using CncModels.Entity;
using CncRepository.Interface;
using CncService.Interface;
using CncWebApi.Infrastructure;

namespace CncWebApi.Controllers
{
    /// <summary>
    /// 系统设置控制器
    /// </summary>
    [RoutePrefix("api/admin")]
    [JwtAuthFilter]
    public class SettingsController : ApiController
    {
        private readonly ISysConfigRepository _sysConfigRepository;
        private readonly IWorkshopService _workshopService;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingsController(ISysConfigRepository sysConfigRepository, IWorkshopService workshopService)
        {
            _sysConfigRepository = sysConfigRepository;
            _workshopService = workshopService;
        }

        #region 系统配置

        /// <summary>
        /// 配置项列表
        /// GET /api/admin/sys-config
        /// </summary>
        [HttpGet]
        [Route("sys-config")]
        public IHttpActionResult GetSysConfigList()
        {
            var configs = _sysConfigRepository.GetAll();
            var items = configs.Select(c => new SysConfigListItem
            {
                Id = c.Id,
                ConfigKey = c.ConfigKey,
                ConfigValue = c.ConfigValue,
                ValueType = c.ValueType,
                Description = c.Description
            }).ToList();
            // Mock约定：data: { items: [...] }，不能直接返回数组
            return Ok(ApiResponse<object>.Success(new { items }));
        }

        /// <summary>
        /// 编辑配置项
        /// PUT /api/admin/sys-config/{id}
        /// </summary>
        [HttpPut]
        [Route("sys-config/{id:int}")]
        public IHttpActionResult UpdateSysConfig(int id, [FromBody] UpdateSysConfigRequest request)
        {
            if (request == null) throw new CncService.BusinessException(CncModels.Constants.ErrorCode.BadRequest, "请求参数不能为空");
            var result = _sysConfigRepository.UpdateValue(id, request.ConfigValue);
            return Ok(ApiResponse<object>.Success(null));
        }

        /// <summary>
        /// 修改密码
        /// POST /api/admin/change-password
        /// </summary>
        [HttpPost]
        [Route("change-password")]
        public IHttpActionResult ChangePassword([FromBody] ChangePasswordRequest request)
        {
            if (request == null) throw new CncService.BusinessException(CncModels.Constants.ErrorCode.BadRequest, "请求参数不能为空");
            // 简化实现：更新密码哈希到 SysConfig
            var hash = BCrypt.Net.BCrypt.HashPassword(request.NewPassword);
            var pwdCfg = _sysConfigRepository.GetByKey("admin_password_hash");
            if (pwdCfg == null) throw new CncService.BusinessException(CncModels.Constants.ErrorCode.NotFound, "密码配置未找到");
            _sysConfigRepository.UpdateValue(pwdCfg.Id, hash);
            return Ok(ApiResponse<object>.Success(null));
        }

        #endregion

        #region 车间管理

        /// <summary>
        /// 车间列表
        /// GET /api/admin/workshop
        /// </summary>
        [HttpGet]
        [Route("workshop")]
        public IHttpActionResult GetWorkshopList(string keyword = null)
        {
            var result = _workshopService.GetList(keyword);
            // Mock约定：data: { items: [...] }，不能直接返回数组
            return Ok(ApiResponse<object>.Success(new { items = result }));
        }

        /// <summary>
        /// 新增车间
        /// POST /api/admin/workshop
        /// </summary>
        [HttpPost]
        [Route("workshop")]
        public IHttpActionResult CreateWorkshop([FromBody] CreateWorkshopRequest request)
        {
            var id = _workshopService.Create(request);
            return Ok(ApiResponse<object>.Success(new { id }));
        }

        /// <summary>
        /// 编辑车间
        /// PUT /api/admin/workshop/{id}
        /// </summary>
        [HttpPut]
        [Route("workshop/{id:int}")]
        public IHttpActionResult UpdateWorkshop(int id, [FromBody] UpdateWorkshopRequest request)
        {
            var result = _workshopService.Update(id, request);
            return Ok(ApiResponse<object>.Success(null));
        }

        /// <summary>
        /// 删除车间
        /// DELETE /api/admin/workshop/{id}
        /// </summary>
        [HttpDelete]
        [Route("workshop/{id:int}")]
        public IHttpActionResult DeleteWorkshop(int id)
        {
            var result = _workshopService.Delete(id);
            return Ok(ApiResponse<object>.Success(null));
        }

        /// <summary>
        /// 启停车间
        /// PUT /api/admin/workshop/{id}/toggle
        /// </summary>
        [HttpPut]
        [Route("workshop/{id:int}/toggle")]
        public IHttpActionResult ToggleWorkshop(int id)
        {
            var result = _workshopService.ToggleEnabled(id);
            return Ok(ApiResponse<object>.Success(null));
        }

        #endregion
    }
}
