// Copyright 2018-2025 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Shouldly;
using ZB.MOM.NatsNet.Server.Internal;

namespace ZB.MOM.NatsNet.Server.Tests.Internal;

/// <summary>
/// Tests for <see cref="ClosedRingBuffer"/>.
/// Mirrors server/ring_test.go: TestRBAppendAndLenAndTotal (ID 2794)
/// and TestRBclosedClients (ID 2795).
/// </summary>
public sealed class ClosedRingBufferTests
{
    [Fact]
    public void AppendAndLenAndTotal_ShouldTrackCorrectly()
    {
        // Mirror: TestRBAppendAndLenAndTotal
        var rb = new ClosedRingBuffer(10);

        for (var i = 0; i < 5; i++)
            rb.Append(new ClosedClient());

        rb.Len().ShouldBe(5);
        rb.TotalConns().ShouldBe(5UL);

        for (var i = 0; i < 25; i++)
            rb.Append(new ClosedClient());

        rb.Len().ShouldBe(10);
        rb.TotalConns().ShouldBe(30UL);
    }

    [Fact]
    public void ClosedClients_ShouldReturnChronologicalOrder()
    {
        // Mirror: TestRBclosedClients
        var rb = new ClosedRingBuffer(10);

        // Build master list with identifiable user strings.
        const int max = 100;
        var master = new ClosedClient[max];
        for (var i = 1; i <= max; i++)
            master[i - 1] = new ClosedClient { User = i.ToString() };

        var ui = 0;

        void AddConn()
        {
            ui++;
            rb.Append(new ClosedClient { User = ui.ToString() });
        }

        for (var i = 0; i < max; i++)
        {
            AddConn();

            var ccs = rb.ClosedClients();
            var start = (int)rb.TotalConns() - ccs.Length;
            var ms = master[start..(start + ccs.Length)];

            // Verify order matches master using User strings.
            ccs.Length.ShouldBe(ms.Length);
            for (var j = 0; j < ccs.Length; j++)
                ccs[j]!.User.ShouldBe(ms[j].User, $"iteration {i}, slot {j}");
        }
    }
}
