using System.Net;

namespace Health.WebApi.Middleware;

/// <summary>
/// 全局异常处理中间件——统一返回 {code, data, message} 格式
/// </summary>
public sealed class ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
    private readonly RequestDelegate _next = next;
    private readonly ILogger<ExceptionMiddleware> _logger = logger;

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            // 生产环境不暴露内部异常详情
            _logger.LogError(ex, "未处理的异常: {Path}", context.Request.Path);
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";

            var result = new
            {
                code = 50000,
                data = (object?)null,
                message = "服务器内部错误，请稍后重试"
            };
            await context.Response.WriteAsync(JsonSerializer.Serialize(result));
        }
    }
}
