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

namespace Fast.Shared.Logic;

public class SerilogMiddleware(RequestDelegate 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);
            if (!context.Response.HasStarted)
            {
                // Return as plain text to preserve newlines without JSON escaping
                context.Response.ContentType = "text/plain";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            await context.Response.WriteAsync(innerMsg);
        }
    }
}
