using NATS.E2E.Tests.Infrastructure;

namespace NATS.E2E.Tests;

[Collection("E2E-Gateway")]
public class GatewayTests(GatewayFixture fixture)
{
    [Fact]
    public async Task Gateway_MessageCrossesGateway()
    {
        await using var pub = fixture.CreateClientA();
        await using var sub = fixture.CreateClientB();
        await pub.ConnectAsync();
        await sub.ConnectAsync();

        await using var subscription = await sub.SubscribeCoreAsync<string>("e2e.gw.cross");
        // Ping both sides: subscriber's ping flushes the SUB to server B,
        // publisher's ping ensures server A has received the propagated interest.
        await sub.PingAsync();
        await pub.PingAsync();

        await pub.PublishAsync("e2e.gw.cross", "gateway-msg");

        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var msg = await subscription.Msgs.ReadAsync(cts.Token);
        msg.Data.ShouldBe("gateway-msg");
    }

    [Fact]
    public async Task Gateway_NoInterest_NoDelivery()
    {
        await using var pub = fixture.CreateClientA();
        await using var sub = fixture.CreateClientB();
        await pub.ConnectAsync();
        await sub.ConnectAsync();

        await using var subscription = await sub.SubscribeCoreAsync<string>("e2e.gw.listen");
        // Ping both sides to ensure subscription interest has propagated before publishing.
        await sub.PingAsync();
        await pub.PingAsync();

        await pub.PublishAsync("e2e.gw.nolisten", "should-not-arrive");
        await pub.PublishAsync("e2e.gw.listen", "should-arrive");

        using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        var msg = await subscription.Msgs.ReadAsync(cts.Token);
        msg.Data.ShouldBe("should-arrive");
    }
}
