using System;
using System.Collections.Generic;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.MxAccess;

namespace ZB.MOM.WW.MxGateway.Worker.Tests.MxAccess;

/// <summary>
///     Unit tests for the in-process A.3 dispatcher: prove that
///     <see cref="IMxAccessAlarmConsumer.AlarmTransitionEmitted"/> events
///     fan out to the worker's <see cref="MxAccessEventQueue"/> as proto
///     <see cref="OnAlarmTransitionEvent"/> messages with correctly mapped
///     fields. The fake consumer below stands in for the wnwrap-backed
///     production implementation so this exercise needs no AVEVA install.
/// </summary>
public sealed class AlarmDispatcherTests
{
    private const string SessionId = "session-001";

    /// <summary>Verifies that alarm transitions land in the queue with correctly mapped fields.</summary>
    [Fact]
    public void OnTransition_WhenAlarmTransitionRaised_LandsInQueueWithMappedFields()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        MxAccessEventQueue queue = new MxAccessEventQueue();
        MxAccessAlarmEventSink sink = new MxAccessAlarmEventSink(queue, new MxAccessEventMapper());
        using AlarmDispatcher dispatcher = new AlarmDispatcher(consumer, sink, SessionId);

        DateTime ts = new DateTime(2026, 5, 1, 17, 26, 14, 709, DateTimeKind.Utc);
        consumer.RaiseTransition(new MxAlarmTransitionEvent
        {
            PreviousState = MxAlarmStateKind.Unspecified,
            Record = new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "TestArea",
                TagName = "TestMachine_001.TestAlarm001",
                Type = "DSC",
                Priority = 500,
                State = MxAlarmStateKind.UnackAlm,
                TransitionTimestampUtc = ts,
                AlarmComment = "Test alarm #1",
            },
        });

        Assert.Equal(1, queue.Count);
        Assert.True(queue.TryDequeue(out WorkerEvent? workerEvent));
        Assert.NotNull(workerEvent);
        MxEvent mxEvent = workerEvent!.Event;
        Assert.Equal(MxEventFamily.OnAlarmTransition, mxEvent.Family);
        Assert.Equal(SessionId, mxEvent.SessionId);

        OnAlarmTransitionEvent body = mxEvent.OnAlarmTransition;
        Assert.NotNull(body);
        Assert.Equal("Galaxy!TestArea.TestMachine_001.TestAlarm001", body.AlarmFullReference);
        Assert.Equal("TestMachine_001.TestAlarm001", body.SourceObjectReference);
        Assert.Equal("DSC", body.AlarmTypeName);
        Assert.Equal(AlarmTransitionKind.Raise, body.TransitionKind);
        Assert.Equal(500, body.Severity);
        Assert.Equal("Test alarm #1", body.OperatorComment);
        Assert.Equal("TestArea", body.Category);
        Assert.NotNull(body.TransitionTimestamp);
        Assert.Equal(ts, body.TransitionTimestamp.ToDateTime());
        Assert.False(body.Degraded);
        Assert.Equal(AlarmProviderMode.Alarmmgr, body.SourceProvider);
    }

    /// <summary>
    ///     Verifies that a transition enqueued via the subtag fallback
    ///     (<c>degraded: true</c>) is marked <see cref="OnAlarmTransitionEvent.Degraded"/>
    ///     with <see cref="AlarmProviderMode.Subtag"/>, while the default path
    ///     stays on the alarmmgr parity contract.
    /// </summary>
    [Fact]
    public void EnqueueTransition_WhenDegraded_MarksDegradedAndSubtagProvider()
    {
        MxAccessEventQueue queue = new MxAccessEventQueue();
        MxAccessAlarmEventSink sink = new MxAccessAlarmEventSink(queue, new MxAccessEventMapper());
        sink.Attach(new object(), SessionId);

        DateTime ts = new DateTime(2026, 5, 1, 17, 26, 14, 709, DateTimeKind.Utc);
        sink.EnqueueTransition(
            alarmFullReference: "Galaxy!TestArea.TestMachine_001.TestAlarm001",
            sourceObjectReference: "TestMachine_001.TestAlarm001",
            alarmTypeName: "DSC",
            transitionKind: AlarmTransitionKind.Raise,
            severity: 500,
            originalRaiseTimestampUtc: null,
            transitionTimestampUtc: ts,
            operatorUser: string.Empty,
            operatorComment: string.Empty,
            category: "TestArea",
            description: string.Empty,
            degraded: true);

        Assert.Equal(1, queue.Count);
        Assert.True(queue.TryDequeue(out WorkerEvent? workerEvent));
        OnAlarmTransitionEvent body = workerEvent!.Event.OnAlarmTransition;
        Assert.True(body.Degraded);
        Assert.Equal(AlarmProviderMode.Subtag, body.SourceProvider);
    }

    /// <summary>Verifies that unchanged alarm states do not emit transitions.</summary>
    [Fact]
    public void OnTransition_WithConsecutiveUnchangedState_DoesNotEmitTransition()
    {
        // Mapper.MapTransition returns Unspecified when the state didn't
        // change; the dispatcher should drop the event before queueing.
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        MxAccessEventQueue queue = new MxAccessEventQueue();
        MxAccessAlarmEventSink sink = new MxAccessAlarmEventSink(queue, new MxAccessEventMapper());
        using AlarmDispatcher dispatcher = new AlarmDispatcher(consumer, sink, SessionId);

        consumer.RaiseTransition(new MxAlarmTransitionEvent
        {
            PreviousState = MxAlarmStateKind.UnackAlm,
            Record = new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "X",
                TagName = "Y",
                State = MxAlarmStateKind.UnackAlm,
            },
        });

        Assert.Equal(0, queue.Count);
    }

    /// <summary>Verifies that state transitions are mapped according to the state table.</summary>
    /// <param name="previous">The previous alarm state.</param>
    /// <param name="current">The current alarm state.</param>
    /// <param name="expected">The expected transition kind.</param>
    [Theory]
    [InlineData(MxAlarmStateKind.Unspecified, MxAlarmStateKind.UnackAlm, AlarmTransitionKind.Raise)]
    [InlineData(MxAlarmStateKind.UnackAlm, MxAlarmStateKind.AckAlm, AlarmTransitionKind.Acknowledge)]
    [InlineData(MxAlarmStateKind.UnackAlm, MxAlarmStateKind.UnackRtn, AlarmTransitionKind.Clear)]
    [InlineData(MxAlarmStateKind.UnackRtn, MxAlarmStateKind.UnackAlm, AlarmTransitionKind.Raise)]
    public void MapTransition_ForEachStatePair_FollowsStateTable(
        MxAlarmStateKind previous,
        MxAlarmStateKind current,
        AlarmTransitionKind expected)
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        MxAccessEventQueue queue = new MxAccessEventQueue();
        MxAccessAlarmEventSink sink = new MxAccessAlarmEventSink(queue, new MxAccessEventMapper());
        using AlarmDispatcher dispatcher = new AlarmDispatcher(consumer, sink, SessionId);

        consumer.RaiseTransition(new MxAlarmTransitionEvent
        {
            PreviousState = previous,
            Record = new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "G",
                TagName = "T",
                State = current,
            },
        });

        Assert.Equal(1, queue.Count);
        queue.TryDequeue(out WorkerEvent? evt);
        Assert.Equal(expected, evt!.Event.OnAlarmTransition.TransitionKind);
    }

    /// <summary>Verifies that subscribe calls are forwarded to the consumer.</summary>
    [Fact]
    public void Subscribe_WhenInvoked_ForwardsToConsumer()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        dispatcher.Subscribe(@"\\HOST\Galaxy!Area1");
        Assert.Equal(@"\\HOST\Galaxy!Area1", consumer.LastSubscription);
    }

    /// <summary>Verifies that acknowledge calls are forwarded to the consumer with operator identity.</summary>
    [Fact]
    public void Acknowledge_WhenInvoked_ForwardsToConsumerWithFullOperatorIdentity()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        consumer.AcknowledgeReturn = 0;
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        Guid guid = Guid.NewGuid();
        int rc = dispatcher.Acknowledge(
            guid, "Acked", "alice", "WS01", "CORP", "Alice Smith");

        Assert.Equal(0, rc);
        Assert.Equal(guid, consumer.LastAckGuid);
        Assert.Equal("Acked", consumer.LastAckComment);
        Assert.Equal("alice", consumer.LastAckOperatorName);
        Assert.Equal("WS01", consumer.LastAckOperatorNode);
        Assert.Equal("CORP", consumer.LastAckOperatorDomain);
        Assert.Equal("Alice Smith", consumer.LastAckOperatorFullName);
    }

    /// <summary>Verifies that acknowledge-by-name calls are forwarded to the consumer.</summary>
    [Fact]
    public void AcknowledgeByName_WhenInvoked_ForwardsToConsumerWithFullTuple()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer { AcknowledgeReturn = 0 };
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        int rc = dispatcher.AcknowledgeByName(
            alarmName: "TestMachine_001.TestAlarm001",
            providerName: "Galaxy",
            groupName: "TestArea",
            ackComment: "ack",
            ackOperatorName: "alice",
            ackOperatorNode: "WS",
            ackOperatorDomain: "CORP",
            ackOperatorFullName: "Alice Smith");

        Assert.Equal(0, rc);
        Assert.NotNull(consumer.LastAckByNameTuple);
        Assert.Equal("TestMachine_001.TestAlarm001", consumer.LastAckByNameTuple!.Value.Name);
        Assert.Equal("Galaxy", consumer.LastAckByNameTuple!.Value.Provider);
        Assert.Equal("TestArea", consumer.LastAckByNameTuple!.Value.Group);
    }

    /// <summary>Verifies that consumer alarm records are mapped to proto snapshots.</summary>
    [Fact]
    public void SnapshotActiveAlarms_WhenConsumerHasRecords_MapsRecordsToProtos()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        DateTime ts = new DateTime(2026, 5, 1, 17, 26, 14, 709, DateTimeKind.Utc);
        consumer.SnapshotResult = new[]
        {
            new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "TestArea",
                TagName = "Tag1",
                Type = "DSC",
                Priority = 500,
                State = MxAlarmStateKind.UnackAlm,
                TransitionTimestampUtc = ts,
                AlarmComment = "x",
            },
            new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "TestArea",
                TagName = "Tag2",
                Type = "ANL",
                Priority = 100,
                State = MxAlarmStateKind.AckAlm,
                TransitionTimestampUtc = ts,
            },
        };
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        IReadOnlyList<ActiveAlarmSnapshot> snapshots = dispatcher.SnapshotActiveAlarms(out _);
        Assert.Equal(2, snapshots.Count);

        Assert.Equal("Galaxy!TestArea.Tag1", snapshots[0].AlarmFullReference);
        Assert.Equal(AlarmConditionState.Active, snapshots[0].CurrentState);
        Assert.Equal(500, snapshots[0].Severity);
        Assert.Equal(ts, snapshots[0].LastTransitionTimestamp.ToDateTime());

        Assert.Equal("Galaxy!TestArea.Tag2", snapshots[1].AlarmFullReference);
        Assert.Equal(AlarmConditionState.ActiveAcked, snapshots[1].CurrentState);
    }

    /// <summary>
    ///     Verifies that the per-record subtag-fallback flag flows through the
    ///     snapshot path: a degraded record maps to an
    ///     <see cref="ActiveAlarmSnapshot"/> with <see cref="ActiveAlarmSnapshot.Degraded"/>
    ///     set and <see cref="AlarmProviderMode.Subtag"/>, while a non-degraded
    ///     record stays on the alarmmgr parity contract.
    /// </summary>
    [Fact]
    public void SnapshotActiveAlarms_PropagatesDegradedAndSourceProvider()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        DateTime ts = new DateTime(2026, 5, 1, 17, 26, 14, 709, DateTimeKind.Utc);
        consumer.SnapshotResult = new[]
        {
            new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "TestArea",
                TagName = "Tag1",
                Type = "DSC",
                Priority = 500,
                State = MxAlarmStateKind.UnackAlm,
                TransitionTimestampUtc = ts,
                Degraded = true,
            },
            new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "TestArea",
                TagName = "Tag2",
                Type = "ANL",
                Priority = 100,
                State = MxAlarmStateKind.UnackAlm,
                TransitionTimestampUtc = ts,
                Degraded = false,
            },
        };
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        IReadOnlyList<ActiveAlarmSnapshot> snapshots = dispatcher.SnapshotActiveAlarms(out _);
        Assert.Equal(2, snapshots.Count);

        Assert.True(snapshots[0].Degraded);
        Assert.Equal(AlarmProviderMode.Subtag, snapshots[0].SourceProvider);

        Assert.False(snapshots[1].Degraded);
        Assert.Equal(AlarmProviderMode.Alarmmgr, snapshots[1].SourceProvider);
    }

    /// <summary>
    ///     A truncated consumer snapshot stamps every mapped record with
    ///     <c>FromTruncatedSnapshot</c> and reports the verdict out of the same
    ///     call. Every record carries it because the public QueryActiveAlarms RPC
    ///     streams bare snapshots with no envelope to hold set-level status, so
    ///     a client that reads only one record must still learn the set may be
    ///     incomplete.
    /// </summary>
    [Fact]
    public void SnapshotActiveAlarms_WhenConsumerReportsTruncated_StampsEveryRecord()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer
        {
            SnapshotTruncated = true,
            SnapshotResult = new[]
            {
                NewSnapshotRecord("Tag1", degraded: false),
                NewSnapshotRecord("Tag2", degraded: true),
            },
        };
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        IReadOnlyList<ActiveAlarmSnapshot> snapshots = dispatcher.SnapshotActiveAlarms(out bool truncated);

        Assert.True(truncated);
        Assert.Equal(2, snapshots.Count);
        Assert.All(snapshots, snapshot => Assert.True(snapshot.FromTruncatedSnapshot));
        // Truncation is about the SET; the per-record provider fidelity flag is
        // independent and must not be dragged along with it.
        Assert.False(snapshots[0].Degraded);
        Assert.True(snapshots[1].Degraded);
    }

    /// <summary>
    ///     The control. A complete consumer snapshot must leave every record's
    ///     <c>FromTruncatedSnapshot</c> unset — without this, a field hard-wired
    ///     to true would satisfy the test above and every snapshot would read as
    ///     possibly-incomplete.
    /// </summary>
    [Fact]
    public void SnapshotActiveAlarms_WhenConsumerReportsComplete_LeavesRecordsUnstamped()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer
        {
            SnapshotTruncated = false,
            SnapshotResult = new[] { NewSnapshotRecord("Tag1", degraded: false) },
        };
        using AlarmDispatcher dispatcher = new AlarmDispatcher(
            consumer,
            new MxAccessAlarmEventSink(new MxAccessEventQueue(), new MxAccessEventMapper()),
            SessionId);

        IReadOnlyList<ActiveAlarmSnapshot> snapshots = dispatcher.SnapshotActiveAlarms(out bool truncated);

        Assert.False(truncated);
        Assert.False(Assert.Single(snapshots).FromTruncatedSnapshot);
    }

    private static MxAlarmSnapshotRecord NewSnapshotRecord(string tagName, bool degraded)
    {
        return new MxAlarmSnapshotRecord
        {
            AlarmGuid = Guid.NewGuid(),
            ProviderName = "Galaxy",
            Group = "TestArea",
            TagName = tagName,
            Type = "DSC",
            Priority = 500,
            State = MxAlarmStateKind.UnackAlm,
            Degraded = degraded,
        };
    }

    /// <summary>Verifies that dispose unsubscribes the handler and disposes the consumer.</summary>
    [Fact]
    public void Dispose_WhenSubscribed_UnsubscribesHandlerAndDisposesConsumer()
    {
        FakeAlarmConsumer consumer = new FakeAlarmConsumer();
        MxAccessEventQueue queue = new MxAccessEventQueue();
        MxAccessAlarmEventSink sink = new MxAccessAlarmEventSink(queue, new MxAccessEventMapper());
        AlarmDispatcher dispatcher = new AlarmDispatcher(consumer, sink, SessionId);

        dispatcher.Dispose();

        Assert.True(consumer.Disposed);
        consumer.RaiseTransition(new MxAlarmTransitionEvent
        {
            PreviousState = MxAlarmStateKind.Unspecified,
            Record = new MxAlarmSnapshotRecord
            {
                AlarmGuid = Guid.NewGuid(),
                ProviderName = "Galaxy",
                Group = "G",
                TagName = "T",
                State = MxAlarmStateKind.UnackAlm,
            },
        });
        Assert.Equal(0, queue.Count);
    }

    private sealed class FakeAlarmConsumer : IMxAccessAlarmConsumer
    {
        /// <summary>Raised when an alarm transition occurs.</summary>
        public event EventHandler<MxAlarmTransitionEvent>? AlarmTransitionEmitted;

        /// <summary>Gets the last subscription reference.</summary>
        public string? LastSubscription { get; private set; }
        /// <summary>Gets the GUID from the last acknowledge call.</summary>
        public Guid LastAckGuid { get; private set; }
        /// <summary>Gets the comment from the last acknowledge call.</summary>
        public string? LastAckComment { get; private set; }
        /// <summary>Gets the operator name from the last acknowledge call.</summary>
        public string? LastAckOperatorName { get; private set; }
        /// <summary>Gets the operator node from the last acknowledge call.</summary>
        public string? LastAckOperatorNode { get; private set; }
        /// <summary>Gets the operator domain from the last acknowledge call.</summary>
        public string? LastAckOperatorDomain { get; private set; }
        /// <summary>Gets the operator full name from the last acknowledge call.</summary>
        public string? LastAckOperatorFullName { get; private set; }
        /// <summary>Gets or sets the return code for acknowledge operations.</summary>
        public int AcknowledgeReturn { get; set; }
        /// <summary>Gets or sets the result collection for snapshot operations.</summary>
        public IReadOnlyList<MxAlarmSnapshotRecord> SnapshotResult { get; set; } =
            Array.Empty<MxAlarmSnapshotRecord>();
        /// <summary>Gets a value indicating whether this instance has been disposed.</summary>
        public bool Disposed { get; private set; }

        /// <summary>Raises an alarm transition event.</summary>
        /// <param name="transition">The alarm transition event.</param>
        public void RaiseTransition(MxAlarmTransitionEvent transition)
        {
            AlarmTransitionEmitted?.Invoke(this, transition);
        }

        /// <inheritdoc />
        public void Subscribe(string subscription)
        {
            LastSubscription = subscription;
        }

        /// <inheritdoc />
        public int AcknowledgeByGuid(
            Guid alarmGuid,
            string ackComment,
            string ackOperatorName,
            string ackOperatorNode,
            string ackOperatorDomain,
            string ackOperatorFullName)
        {
            LastAckGuid = alarmGuid;
            LastAckComment = ackComment;
            LastAckOperatorName = ackOperatorName;
            LastAckOperatorNode = ackOperatorNode;
            LastAckOperatorDomain = ackOperatorDomain;
            LastAckOperatorFullName = ackOperatorFullName;
            return AcknowledgeReturn;
        }

        /// <inheritdoc />
        public int AcknowledgeByName(
            string alarmName, string providerName, string groupName,
            string ackComment, string ackOperatorName, string ackOperatorNode,
            string ackOperatorDomain, string ackOperatorFullName)
        {
            LastAckByNameTuple = (alarmName, providerName, groupName);
            LastAckOperatorName = ackOperatorName;
            return AcknowledgeReturn;
        }

        /// <summary>Gets the last acknowledge-by-name tuple (alarm name, provider, group).</summary>
        public (string Name, string Provider, string Group)? LastAckByNameTuple { get; private set; }

        /// <summary>Gets or sets the truncation verdict this consumer reports with its snapshot.</summary>
        public bool SnapshotTruncated { get; set; }

        /// <inheritdoc />
        public IReadOnlyList<MxAlarmSnapshotRecord> SnapshotActiveAlarms(out bool truncated)
        {
            truncated = SnapshotTruncated;
            return SnapshotResult;
        }

        /// <summary>Gets the count of poll operations.</summary>
        public int PollCount { get; private set; }

        /// <inheritdoc />
        public void PollOnce()
        {
            PollCount++;
        }

        /// <inheritdoc />
        public void Dispose()
        {
            Disposed = true;
        }
    }
}
