using KArtSell.Host.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

namespace KArtSell.Integration.Tests;

public sealed class CorrelationIdMiddlewareTests
{
    [Fact]
    public async Task Preserves_valid_header_and_exposes_one_boundary_identifier()
    {
        var expected = Guid.Parse("11111111-1111-1111-1111-111111111111");
        var context = new DefaultHttpContext();
        context.Request.Headers["X-Correlation-Id"] = expected.ToString("D");
        var nextCalled = false;
        var middleware = new CorrelationIdMiddleware(_ =>
        {
            nextCalled = true;
            return Task.CompletedTask;
        }, NullLogger<CorrelationIdMiddleware>.Instance);

        await middleware.InvokeAsync(context);

        Assert.True(nextCalled);
        Assert.Equal(expected.ToString("D"), context.TraceIdentifier);
        Assert.Equal(expected, Assert.IsType<Guid>(context.Items["CorrelationId"]));
        Assert.Equal(expected.ToString("D"), context.Response.Headers["X-Correlation-Id"].ToString());
    }

    [Fact]
    public async Task Replaces_invalid_or_empty_header_without_reusing_client_value()
    {
        var context = new DefaultHttpContext();
        context.Request.Headers["X-Correlation-Id"] = "not-a-guid";
        var middleware = new CorrelationIdMiddleware(_ => Task.CompletedTask, NullLogger<CorrelationIdMiddleware>.Instance);

        await middleware.InvokeAsync(context);

        var correlationId = Assert.IsType<Guid>(context.Items["CorrelationId"]);
        Assert.NotEqual(Guid.Empty, correlationId);
        Assert.Equal(correlationId.ToString("D"), context.TraceIdentifier);
        Assert.Equal(correlationId.ToString("D"), context.Response.Headers["X-Correlation-Id"].ToString());
    }
}
