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();
        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();
        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>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);
        }

        /// <summary>Records the subscription reference.</summary>
        /// <param name="subscription">The subscription reference.</param>
        public void Subscribe(string subscription)
        {
            LastSubscription = subscription;
        }

        /// <summary>Records an acknowledge-by-GUID call with operator identity.</summary>
        /// <param name="alarmGuid">The alarm GUID.</param>
        /// <param name="ackComment">The acknowledgment comment.</param>
        /// <param name="ackOperatorName">The operator name.</param>
        /// <param name="ackOperatorNode">The operator node.</param>
        /// <param name="ackOperatorDomain">The operator domain.</param>
        /// <param name="ackOperatorFullName">The operator full name.</param>
        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;
        }

        /// <summary>Records an acknowledge-by-name call with alarm name, provider, and group.</summary>
        /// <param name="alarmName">The alarm name.</param>
        /// <param name="providerName">The provider name.</param>
        /// <param name="groupName">The alarm group name.</param>
        /// <param name="ackComment">The acknowledgment comment.</param>
        /// <param name="ackOperatorName">The operator name.</param>
        /// <param name="ackOperatorNode">The operator node.</param>
        /// <param name="ackOperatorDomain">The operator domain.</param>
        /// <param name="ackOperatorFullName">The operator full name.</param>
        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>Returns the current snapshot result collection.</summary>
        public IReadOnlyList<MxAlarmSnapshotRecord> SnapshotActiveAlarms()
        {
            return SnapshotResult;
        }

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

        /// <summary>Increments the poll count.</summary>
        public void PollOnce()
        {
            PollCount++;
        }

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