using System.Net;
using Newtonsoft.Json;
using Serilog.Context;

namespace Fast.Logic;

public class SerilogMiddleware
{
    private readonly RequestDelegate next;

    public SerilogMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            var appUserId = Util.GetAppUserId(context.User);
            LogContext.PushProperty("UserID", appUserId);

            //if an error occurs here it will still get logged even though we swallow it with "catch (Exception ex)"
            await next(context);
        }
        catch (Exception ex)
        {
            string innerMsg = Util.String.GetExceptionMessage(ex);
            var result = JsonConvert.SerializeObject(innerMsg);
            if (!context.Response.HasStarted)
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            await context.Response.WriteAsync(result);
        }
    }
}
