using HoneyBox.Admin.Models.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace HoneyBox.Admin.Filters;

/// <summary>
/// 管理系统全局异常过滤器
/// </summary>
public class AdminExceptionFilter : IExceptionFilter
{
    private readonly ILogger<AdminExceptionFilter> _logger;

    public AdminExceptionFilter(ILogger<AdminExceptionFilter> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 处理异常
    /// </summary>
    public void OnException(ExceptionContext context)
    {
        if (context.Exception is AdminException adminException)
        {
            // 业务异常
            _logger.LogWarning(adminException, "业务异常: {Message}", adminException.Message);
            
            var statusCode = adminException.Code switch
            {
                >= 40001 and <= 40099 => StatusCodes.Status401Unauthorized, // 认证错误
                >= 40101 and <= 40199 => StatusCodes.Status403Forbidden,    // 授权错误
                >= 40201 and <= 40299 => StatusCodes.Status400BadRequest,   // 验证错误
                _ => StatusCodes.Status500InternalServerError               // 服务器错误
            };

            context.Result = new JsonResult(ApiResponse.Error(adminException.Code, adminException.Message))
            {
                StatusCode = statusCode
            };
            context.ExceptionHandled = true;
        }
        else
        {
            // 未处理的异常
            _logger.LogError(context.Exception, "未处理的异常: {Message}", context.Exception.Message);
            
            context.Result = new JsonResult(ApiResponse.Error(
                AdminErrorCodes.InternalError, 
                "服务器内部错误"))
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };
            context.ExceptionHandled = true;
        }
    }
}
