using Long.Core.Api;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Text.Json;

namespace Long.Core.Middleware;

/// <summary>
/// 异常捕获中间件
/// </summary>
public class LongExceptionCatch
{
    /// <summary>
    /// 请求委托
    /// </summary>
    private readonly RequestDelegate _requestDelegate;

    public LongExceptionCatch(RequestDelegate requestDelegate)
    {
        _requestDelegate = requestDelegate;
    }

    /// <summary>
    /// 唤起
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    public async Task Invoke(HttpContext httpContext)
    {
        try
        {

            await _requestDelegate(httpContext);
        }
        catch (Exception ex)
        {
            httpContext.Response.StatusCode = 500;
            httpContext.Response.ContentType = "application/json;charset=utf-8";

            var result = new LongExceptionOutput()
            {
                Success = false,
                Message = "服务器内部错误：" + ex.Message,
                StatusCode = (int)HttpStatusCode.InternalServerError,
                Source = ex.Source ?? "",
                StackTrace = ex.StackTrace ?? "",
                TargetSite = ex.TargetSite,
                Data = ex.Data
            };

            await httpContext.Response.WriteAsync(JsonSerializer.Serialize(result));
        }
    }
}
