using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Communication;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;

/// <summary>
/// Unit tests for <see cref="SharedAlarmSummaryService"/> (arch-review WP2.4). The Alarm
/// Summary page polls per circuit; the shared façade must collapse those into ONE per-site
/// fan-out per freshness window, and must widen that window while the live alarm cache is
/// serving the site (where the poll only still supplies the not-reporting list).
/// </summary>
public class SharedAlarmSummaryServiceTests : IDisposable
{
    private const int SiteId = 7;
    private const string SiteIdentifier = "plant-a";

    private static readonly DateTimeOffset T0 = new(2026, 8, 14, 9, 0, 0, TimeSpan.Zero);

    private readonly ITemplateEngineRepository _instanceRepo = Substitute.For<ITemplateEngineRepository>();
    private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
    private readonly IInstanceSnapshotClient _snapshotClient = Substitute.For<IInstanceSnapshotClient>();
    private readonly FakeLiveCache _liveCache = new();
    private readonly ServiceProvider _provider;

    private DateTimeOffset _now = T0;

    public SharedAlarmSummaryServiceTests()
    {
        _siteRepo.GetSiteByIdAsync(SiteId, Arg.Any<CancellationToken>())
            .Returns(new Site("Plant A", SiteIdentifier) { Id = SiteId });
        _instanceRepo.GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>())
            .Returns(new List<Instance>
            {
                new("inst-a") { Id = 1, SiteId = SiteId, State = InstanceState.Enabled },
            });
        _snapshotClient.GetSnapshotAsync(SiteIdentifier, "inst-a", Arg.Any<CancellationToken>())
            .Returns(new DebugViewSnapshot(
                "inst-a",
                Array.Empty<AttributeValueChanged>(),
                new[] { new AlarmStateChanged("inst-a", "A-alarm", AlarmState.Active, 500, T0) },
                T0));

        var services = new ServiceCollection();
        services.AddSingleton(_instanceRepo);
        services.AddSingleton(_siteRepo);
        services.AddSingleton(_snapshotClient);
        services.AddScoped<AlarmSummaryService>();
        _provider = services.BuildServiceProvider();
    }

    private SharedAlarmSummaryService CreateSut() =>
        new(_provider.GetRequiredService<IServiceScopeFactory>(), _liveCache, () => _now);

    [Fact]
    public async Task ConcurrentCircuits_ShareOneFanOut()
    {
        var sut = CreateSut();

        var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => sut.GetSiteAlarmsAsync(SiteId)));

        await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
        Assert.All(results, r => Assert.Single(r.Alarms));
    }

    [Fact]
    public async Task ColdLiveCache_RefreshesWithinThePageTick()
    {
        var sut = CreateSut();
        _liveCache.Live = false;

        await sut.GetSiteAlarmsAsync(SiteId);
        // The page polls every 15s and, while the cache is cold, the poll is its
        // authoritative rebuild — so the memo must have expired by then.
        _now = T0.AddSeconds(15);
        await sut.GetSiteAlarmsAsync(SiteId);

        await _instanceRepo.Received(2).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task LiveCacheServing_SkipsTheFanOutEntirely()
    {
        // The aggregator's seed/reconcile already ran this exact fan-out and publishes both
        // halves of the answer, so the façade must not run a second one — not now, not after
        // any elapsed window (arch-review phase-2 residual #4).
        var sut = CreateSut();
        _liveCache.Live = true;
        _liveCache.NotReporting = new[] { "inst-silent" };
        _liveCache.Current = new[]
        {
            new AlarmStateChanged("inst-a", "A-alarm", AlarmState.Active, 500, T0),
        };

        var first = await sut.GetSiteAlarmsAsync(SiteId);
        _now = T0.AddSeconds(61);
        var second = await sut.GetSiteAlarmsAsync(SiteId);

        await _instanceRepo.DidNotReceive().GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
        await _snapshotClient.DidNotReceive().GetSnapshotAsync(
            Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());

        // Both halves come from the cache: the rows so a liveness flip mid-call lands on
        // last-known state instead of a blank grid, and the not-reporting names the page shows.
        foreach (var result in new[] { first, second })
        {
            Assert.Equal("A-alarm", Assert.Single(result.Alarms).Alarm.AlarmName);
            Assert.Equal("inst-silent", Assert.Single(result.NotReportingInstances));
        }
    }

    [Fact]
    public async Task LiveCacheGoingCold_FallsBackToTheFanOut()
    {
        var sut = CreateSut();
        _liveCache.Live = true;

        await sut.GetSiteAlarmsAsync(SiteId);
        await _instanceRepo.DidNotReceive().GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());

        // Aggregator died / stream degraded → the poll is the page's rebuild path again.
        _liveCache.Live = false;
        var result = await sut.GetSiteAlarmsAsync(SiteId);

        await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
        Assert.Single(result.Alarms);
    }

    [Fact]
    public async Task DifferentSites_DoNotShareAMemoSlot()
    {
        const int otherSite = 8;
        _siteRepo.GetSiteByIdAsync(otherSite, Arg.Any<CancellationToken>())
            .Returns(new Site("Plant B", "plant-b") { Id = otherSite });
        _instanceRepo.GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>())
            .Returns(new List<Instance>());

        var sut = CreateSut();

        await sut.GetSiteAlarmsAsync(SiteId);
        await sut.GetSiteAlarmsAsync(otherSite);

        await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
        await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>());
    }

    [Fact]
    public void PureMethods_MatchTheDirectImplementation()
    {
        var sut = CreateSut();
        var direct = new AlarmSummaryService(_instanceRepo, _siteRepo, _snapshotClient);
        var alarms = new List<AlarmStateChanged>
        {
            new("inst-b", "B-alarm", AlarmState.Active, 900, T0),
            new("inst-a", "A-alarm", AlarmState.Normal, 100, T0),
        };

        var shared = sut.BuildFromLiveAlarms(alarms);
        var expected = direct.BuildFromLiveAlarms(alarms);

        Assert.Equal(
            expected.Alarms.Select(r => r.Alarm.AlarmName),
            shared.Alarms.Select(r => r.Alarm.AlarmName));
        var expectedRollup = direct.ComputeRollup(expected.Alarms);
        var sharedRollup = sut.ComputeRollup(shared.Alarms);
        Assert.Equal(expectedRollup.TotalActive, sharedRollup.TotalActive);
        Assert.Equal(expectedRollup.WorstSeverity, sharedRollup.WorstSeverity);
        Assert.Equal(expectedRollup.UnackedCount, sharedRollup.UnackedCount);
        Assert.Equal(expectedRollup.CountsByKind, sharedRollup.CountsByKind);
    }

    public void Dispose() => _provider.Dispose();

    /// <summary>
    /// Read-side stub: liveness, the published alarm snapshot, and the aggregator's
    /// not-reporting set — the three things the façade reads while the cache is serving a site.
    /// </summary>
    private sealed class FakeLiveCache : ISiteAlarmLiveCache
    {
        public bool Live { get; set; }
        public IReadOnlyList<AlarmStateChanged> Current { get; set; } = Array.Empty<AlarmStateChanged>();
        public IReadOnlyList<string> NotReporting { get; set; } = Array.Empty<string>();

        public IDisposable Subscribe(int siteId, Action onChanged) => new NoOp();

        public IReadOnlyList<AlarmStateChanged> GetCurrentAlarms(int siteId) => Current;

        public bool IsLive(int siteId) => Live;

        public IReadOnlyList<string> GetNotReportingInstances(int siteId) => NotReporting;

        private sealed class NoOp : IDisposable
        {
            public void Dispose() { }
        }
    }
}
