using Serilog.Context;

public sealed class CorrelationIdMiddleware
{
    private const string Header = "X-Correlation-Id";
    private readonly RequestDelegate _next;

    public CorrelationIdMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext ctx)
    {
        var correlationId = ctx.Request.Headers[Header].FirstOrDefault()
            ?? Guid.NewGuid().ToString();

        ctx.Response.Headers[Header] = correlationId;

        using(LogContext.PushProperty("CorrelationId", correlationId))
        {
            await _next(ctx);
        } 
    }
}