using HoneyBox.Model.Base;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace HoneyBox.Api.Filters;

/// <summary>
/// 全局异常处理过滤器
/// </summary>
public class GlobalExceptionFilter : IExceptionFilter
{
    private readonly ILogger<GlobalExceptionFilter> _logger;
    private readonly IHostEnvironment _environment;

    public GlobalExceptionFilter(
        ILogger<GlobalExceptionFilter> logger,
        IHostEnvironment environment)
    {
        _logger = logger;
        _environment = environment;
    }

    public void OnException(ExceptionContext context)
    {
        // 记录异常日志
        _logger.LogError(context.Exception, 
            "Unhandled exception occurred. Path: {Path}, Method: {Method}",
            context.HttpContext.Request.Path,
            context.HttpContext.Request.Method);

        // 构建错误响应
        var response = _environment.IsDevelopment()
            ? ApiResponse.Fail($"服务器内部错误: {context.Exception.Message}", 0)
            : ApiResponse.Fail("服务器内部错误", 0);

        context.Result = new ObjectResult(response)
        {
            StatusCode = 200 // 返回 200 状态码，错误信息在响应体中
        };

        context.ExceptionHandled = true;
    }
}
