using Serilog.Context;

namespace MyNewProjectName.WebAPI.Middleware;

/// <summary>
/// Middleware to generate and track correlation ID for each request
/// This ID is added to HTTP headers and Serilog log context for easy tracing
/// </summary>
public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    private const string CorrelationIdHeaderName = "X-Correlation-ID";
    private const string CorrelationIdLogPropertyName = "CorrelationId";

    public CorrelationIdMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Get correlation ID from request header, or generate a new one
        var correlationId = context.Request.Headers[CorrelationIdHeaderName].FirstOrDefault()
            ?? $"req-{Guid.NewGuid():N}";

        // Add correlation ID to response header
        context.Response.Headers[CorrelationIdHeaderName] = correlationId;

        // Add correlation ID to Serilog log context
        // All logs within this request will automatically include this correlation ID
        using (LogContext.PushProperty(CorrelationIdLogPropertyName, correlationId))
        {
            await _next(context);
        }
    }
}
