using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;

namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;

/// <summary>
/// Test double for <see cref="ISubscriptionAdapter" /> used to drive monitored-item behavior in shared-client tests.
/// </summary>
internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
{
    private readonly
        Dictionary<uint, (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback
            )> _items = new();

    // Guards _items so concurrent-subscription tests exercise the production
    // locking rather than tripping over the test double's own state.
    private readonly object _itemsLock = new();

    private uint _nextHandle = 100;
    /// <summary>
    /// Gets a value indicating whether the fake subscription has been deleted.
    /// </summary>
    public bool Deleted { get; private set; }

    /// <summary>
    /// Gets a value indicating whether a condition refresh was requested by the client under test.
    /// </summary>
    public bool ConditionRefreshCalled { get; private set; }

    /// <summary>
    /// Gets or sets a value indicating whether condition refresh should throw to simulate unsupported servers.
    /// </summary>
    public bool ThrowOnConditionRefresh { get; set; }
    /// <summary>Gets the number of times AddDataChangeMonitoredItemAsync was called.</summary>
    public int AddDataChangeCount { get; private set; }

    /// <summary>Gets the number of times AddEventMonitoredItemAsync was called.</summary>
    public int AddEventCount { get; private set; }

    /// <summary>Gets the number of times RemoveMonitoredItemAsync was called.</summary>
    public int RemoveCount { get; private set; }

    /// <summary>
    ///     Gets the handles of all active items.
    /// </summary>
    public IReadOnlyCollection<uint> ActiveHandles
    {
        get
        {
            lock (_itemsLock) return _items.Keys.ToList();
        }
    }

    /// <inheritdoc />
    public uint SubscriptionId { get; set; } = 42;

    /// <inheritdoc />
    public Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs,
        Action<string, DataValue> onDataChange, CancellationToken ct)
    {
        lock (_itemsLock)
        {
            AddDataChangeCount++;
            var handle = _nextHandle++;
            _items[handle] = (nodeId, onDataChange, null);
            return Task.FromResult(handle);
        }
    }

    /// <inheritdoc />
    public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
    {
        lock (_itemsLock)
        {
            RemoveCount++;
            _items.Remove(clientHandle);
        }

        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter,
        Action<EventFieldList> onEvent, CancellationToken ct)
    {
        lock (_itemsLock)
        {
            AddEventCount++;
            var handle = _nextHandle++;
            _items[handle] = (nodeId, null, onEvent);
            return Task.FromResult(handle);
        }
    }

    /// <inheritdoc />
    public Task ConditionRefreshAsync(CancellationToken ct)
    {
        ConditionRefreshCalled = true;
        if (ThrowOnConditionRefresh)
            throw new InvalidOperationException("Condition refresh not supported");
        return Task.CompletedTask;
    }

    /// <summary>
    /// Gets the cancellation token that was supplied to the most recent <see cref="DeleteAsync"/> call,
    /// so tests can assert the CT from the caller is honoured (Client.Shared-014).
    /// </summary>
    public CancellationToken? LastDeleteCt { get; private set; }

    /// <inheritdoc />
    public Task DeleteAsync(CancellationToken ct)
    {
        Deleted = true;
        LastDeleteCt = ct;
        lock (_itemsLock) _items.Clear();
        return Task.CompletedTask;
    }

    /// <summary>
    /// Clears tracked monitored items when the fake subscription is disposed by the client under test.
    /// </summary>
    public void Dispose()
    {
        lock (_itemsLock) _items.Clear();
    }

    /// <summary>
    ///     Simulates a data change notification for testing.
    /// </summary>
    /// <param name="handle">The monitored item handle.</param>
    /// <param name="value">The new data value to simulate.</param>
    public void SimulateDataChange(uint handle, DataValue value)
    {
        (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback) item;
        lock (_itemsLock)
        {
            if (!_items.TryGetValue(handle, out item)) return;
        }

        item.DataCallback?.Invoke(item.NodeId.ToString(), value);
    }

    /// <summary>
    ///     Simulates an event notification for testing.
    /// </summary>
    /// <param name="handle">The monitored item handle.</param>
    /// <param name="eventFields">The event field list to simulate.</param>
    public void SimulateEvent(uint handle, EventFieldList eventFields)
    {
        (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback) item;
        lock (_itemsLock)
        {
            if (!_items.TryGetValue(handle, out item)) return;
        }

        item.EventCallback?.Invoke(eventFields);
    }
}
