using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using CncModels.Dto;
using CncService;
using log4net;

namespace CncWebApi.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// 统一捕获所有未处理异常，转换为标准ApiResponse格式
    /// Controller层不需要 try-catch，异常会自动被此过滤器捕获
    /// </summary>
    public class GlobalExceptionFilter : ExceptionFilterAttribute
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(GlobalExceptionFilter));

        /// <summary>
        /// 异常发生时自动调用
        /// </summary>
        /// <param name="context">异常上下文</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is BusinessException bex)
            {
                // 业务异常：返回对应的错误码和消息
                _log.Warn($"业务异常: [{bex.Code}] {bex.Message}");
                var response = ApiResponse<object>.Fail(bex.Code, bex.Message);
                context.Response = context.Request.CreateResponse(
                    HttpStatusCode.OK, response);
            }
            else
            {
                // 未预期异常：返回通用错误提示，不暴露内部细节
                var requestUrl = context.Request?.RequestUri?.ToString();
                _log.Error($"未处理异常: {requestUrl}", context.Exception);
                var response = ApiResponse<object>.Fail(
                    CncModels.Constants.ErrorCode.InternalError,
                    "服务器内部错误，请稍后重试");
                context.Response = context.Request.CreateResponse(
                    HttpStatusCode.InternalServerError, response);
            }
        }
    }
}
