using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
using ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;

namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;

public sealed class DashboardSnapshotPublisherTests
{
    private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(5);

    /// <summary>
    /// Server-042 regression: a transient failure inside
    /// <see cref="IDashboardSnapshotService.WatchSnapshotsAsync"/> must not
    /// end the BackgroundService; the publisher must wait the configured
    /// reconnect delay and then re-open the subscription. Before the fix,
    /// the publisher exited on the first non-cancellation exception and
    /// the dashboard's snapshot stream went silent until process restart.
    /// </summary>
    [Fact]
    public async Task ExecuteAsync_WhenSnapshotServiceThrowsOnce_ReconnectsAfterDelay()
    {
        ThrowOnceThenYieldSnapshotService snapshotService = new();
        RecordingHubContext hubContext = new();
        TimeSpan reconnectDelay = TimeSpan.FromMilliseconds(50);
        DashboardSnapshotPublisher publisher = new(
            snapshotService,
            hubContext,
            NullLogger<DashboardSnapshotPublisher>.Instance,
            reconnectDelay);

        using CancellationTokenSource cts = new();
        DateTimeOffset startedAt = DateTimeOffset.UtcNow;
        Task execute = publisher.StartAsync(cts.Token);
        await execute.WaitAsync(TestTimeout);

        // The publisher's first WatchSnapshotsAsync call throws; the second
        // call yields one snapshot. We block here until the publisher has
        // made the second subscribe attempt AND broadcast its first
        // snapshot — proving the publisher did NOT exit on the throw.
        await WaitUntilAsync(() => snapshotService.SubscribeCount >= 2);
        await WaitUntilAsync(() => hubContext.SendCount >= 1);

        DateTimeOffset secondSubscribeAt = snapshotService.SecondSubscribeAt
            ?? throw new InvalidOperationException("Second subscribe did not record a timestamp.");

        await cts.CancelAsync();
        await publisher.StopAsync(CancellationToken.None);

        Assert.True(snapshotService.SubscribeCount >= 2,
            $"Expected at least 2 subscribe calls, got {snapshotService.SubscribeCount}.");
        Assert.True(hubContext.SendCount >= 1);

        // The gap between the throw (first subscribe) and the reconnect
        // (second subscribe) is bounded below by the reconnect delay. We
        // give a small slack (10ms) for scheduling jitter on slow CI VMs.
        TimeSpan gap = secondSubscribeAt - startedAt;
        Assert.True(gap >= reconnectDelay - TimeSpan.FromMilliseconds(10),
            $"Expected reconnect gap >= {reconnectDelay.TotalMilliseconds}ms; got {gap.TotalMilliseconds}ms.");
    }

    /// <summary>
    /// Sanity: a normal completion of WatchSnapshotsAsync (no exception)
    /// also reconnects after the delay — exits only on host shutdown.
    /// </summary>
    [Fact]
    public async Task ExecuteAsync_WhenSnapshotServiceCompletes_ReconnectsAfterDelay()
    {
        CompleteImmediatelySnapshotService snapshotService = new();
        RecordingHubContext hubContext = new();
        TimeSpan reconnectDelay = TimeSpan.FromMilliseconds(50);
        DashboardSnapshotPublisher publisher = new(
            snapshotService,
            hubContext,
            NullLogger<DashboardSnapshotPublisher>.Instance,
            reconnectDelay);

        using CancellationTokenSource cts = new();
        Task execute = publisher.StartAsync(cts.Token);
        await execute.WaitAsync(TestTimeout);

        await WaitUntilAsync(() => snapshotService.SubscribeCount >= 2);

        await cts.CancelAsync();
        await publisher.StopAsync(CancellationToken.None);

        Assert.True(snapshotService.SubscribeCount >= 2);
    }

    private static async Task WaitUntilAsync(Func<bool> predicate)
    {
        using CancellationTokenSource cancellationTokenSource = new(TestTimeout);
        while (!predicate())
        {
            await Task.Delay(TimeSpan.FromMilliseconds(5), cancellationTokenSource.Token);
        }
    }

    private sealed class ThrowOnceThenYieldSnapshotService : IDashboardSnapshotService
    {
        public int SubscribeCount { get; private set; }
        public DateTimeOffset? SecondSubscribeAt { get; private set; }

        public DashboardSnapshot GetSnapshot()
        {
            return null!;
        }

        public async IAsyncEnumerable<DashboardSnapshot> WatchSnapshotsAsync(
            [EnumeratorCancellation] CancellationToken cancellationToken)
        {
            SubscribeCount++;
            int call = SubscribeCount;

            if (call == 1)
            {
                // First call: throw after a brief yield so the publisher
                // observes us as a live producer that failed.
                await Task.Yield();
                throw new InvalidOperationException("simulated transient snapshot failure");
            }

            SecondSubscribeAt = DateTimeOffset.UtcNow;
            yield return GetSnapshot();

            // Stay open until cancelled so the publisher's inner await
            // foreach doesn't immediately re-loop.
            try
            {
                await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
            }
        }
    }

    private sealed class CompleteImmediatelySnapshotService : IDashboardSnapshotService
    {
        public int SubscribeCount { get; private set; }

        public DashboardSnapshot GetSnapshot()
        {
            return null!;
        }

#pragma warning disable CS1998 // async without await — IAsyncEnumerable contract requires async signature
        public async IAsyncEnumerable<DashboardSnapshot> WatchSnapshotsAsync(
            [EnumeratorCancellation] CancellationToken cancellationToken)
#pragma warning restore CS1998
        {
            SubscribeCount++;
            // Yield nothing and complete immediately — simulates a transient
            // upstream disconnect that completes cleanly.
            yield break;
        }
    }

    private sealed class RecordingHubContext : IHubContext<DashboardSnapshotHub>
    {
        private readonly RecordingHubClients _clients = new();

        public IHubClients Clients => _clients;
        public IGroupManager Groups { get; } = new NoopGroupManager();

        public int SendCount => _clients.AllProxy.SendCount;
    }

    private sealed class RecordingHubClients : IHubClients
    {
        public RecordingClientProxy AllProxy { get; } = new();

        public IClientProxy All => AllProxy;
        public IClientProxy AllExcept(IReadOnlyList<string> excludedConnectionIds) => AllProxy;
        public IClientProxy Client(string connectionId) => AllProxy;
        public IClientProxy Clients(IReadOnlyList<string> connectionIds) => AllProxy;
        public IClientProxy Group(string groupName) => AllProxy;
        public IClientProxy GroupExcept(string groupName, IReadOnlyList<string> excludedConnectionIds) => AllProxy;
        public IClientProxy Groups(IReadOnlyList<string> groupNames) => AllProxy;
        public IClientProxy User(string userId) => AllProxy;
        public IClientProxy Users(IReadOnlyList<string> userIds) => AllProxy;
    }

    private sealed class RecordingClientProxy : IClientProxy
    {
        private int _sendCount;

        public int SendCount => Volatile.Read(ref _sendCount);

        public Task SendCoreAsync(string method, object?[] args, CancellationToken cancellationToken = default)
        {
            Interlocked.Increment(ref _sendCount);
            return Task.CompletedTask;
        }
    }

    private sealed class NoopGroupManager : IGroupManager
    {
        public Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
            => Task.CompletedTask;

        public Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
            => Task.CompletedTask;
    }
}
