using System.Collections.Concurrent;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;

namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;

/// <summary>
/// In-memory batch-capable <see cref="IDataConnection"/> for the WP2.1b seam tests. It
/// records every batch call (so "one round trip per chunk, not per tag" is assertable),
/// can fail individual tags or a whole batch, and can hang its bulk read so the seed
/// deadline is observable.
/// </summary>
public sealed class FakeBatchDataConnection
    : IDataConnection, IBatchSubscribableConnection, IAlarmSubscribableConnection
{
    private int _nextId;

    /// <summary>Tag lists handed to <see cref="SubscribeBatchAsync"/>, one entry per call.</summary>
    public readonly ConcurrentQueue<IReadOnlyList<string>> SubscribeBatches = new();
    /// <summary>Id lists handed to <see cref="UnsubscribeBatchAsync"/>, one entry per call.</summary>
    public readonly ConcurrentQueue<IReadOnlyList<string>> UnsubscribeBatches = new();
    /// <summary>Tag lists handed to <see cref="ReadBatchAsync"/>, one entry per call.</summary>
    public readonly ConcurrentQueue<IReadOnlyList<string>> ReadBatches = new();
    /// <summary>Count of SINGLE-tag subscribe calls; must stay 0 on a batch-capable adapter.</summary>
    public int SingleSubscribeCalls;
    /// <summary>Count of SINGLE-tag read calls; must stay 0 on a batch-capable adapter.</summary>
    public int SingleReadCalls;
    /// <summary>Wall-clock instant of each <see cref="SubscribeBatchAsync"/> call.</summary>
    public readonly ConcurrentQueue<DateTimeOffset> SubscribeBatchTimes = new();

    /// <summary>Tags reported as failed rows (per-tag resolution failure).</summary>
    public readonly HashSet<string> FailingTags = new(StringComparer.Ordinal);
    /// <summary>
    /// When set, a batch subscribe throws whatever this returns — a batch-level fault.
    /// Returning <c>null</c> lets that call through, so a test can make the fault TRANSIENT
    /// (e.g. fail the initial subscribe at connection level, then let the reconnect
    /// re-subscribe succeed).
    /// </summary>
    public Func<Exception?>? BatchSubscribeThrows;
    /// <summary>When true, bulk reads never return until the caller's token cancels.</summary>
    public bool HangReads;
    /// <summary>
    /// When set, <see cref="SubscribeBatchAsync"/> records the call and then parks until this
    /// task completes, before producing its result rows. Lets a test hold a subscribe batch
    /// in flight while it drives other messages into the actor (e.g. an unsubscribe that
    /// races the completion).
    /// </summary>
    public Task? SubscribeGate;
    /// <summary>Value returned for every readable tag.</summary>
    public object? SeedValue = 42;

    /// <summary>Callback the last batch subscribe registered; drives value pushes in tests.</summary>
    public SubscriptionCallback? ValueCallback;
    /// <summary>Callback the last alarm subscribe registered.</summary>
    public AlarmTransitionCallback? AlarmCallback;

    /// <inheritdoc />
    public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected;

    /// <inheritdoc />
    public event Action? Disconnected;

    /// <summary>Raises <see cref="Disconnected"/> as a real adapter would on a transport fault.</summary>
    public void RaiseDisconnected() => Disconnected?.Invoke();

    /// <inheritdoc />
    public Task ConnectAsync(IDictionary<string, string> connectionDetails, CancellationToken cancellationToken = default)
    {
        Status = ConnectionHealth.Connected;
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task DisconnectAsync(CancellationToken cancellationToken = default)
    {
        Status = ConnectionHealth.Disconnected;
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public async Task<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
        IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
    {
        SubscribeBatches.Enqueue(tagPaths.ToList());
        SubscribeBatchTimes.Enqueue(DateTimeOffset.UtcNow);
        ValueCallback = callback;

        if (BatchSubscribeThrows?.Invoke() is { } fault)
            throw fault;

        if (SubscribeGate is { } gate)
            await gate;

        IReadOnlyList<TagSubscribeResult> rows = tagPaths
            .Select(t => FailingTags.Contains(t)
                ? new TagSubscribeResult(t, false, null, "node not found")
                : new TagSubscribeResult(t, true, $"sub-{Interlocked.Increment(ref _nextId)}", null))
            .ToList();
        return rows;
    }

    /// <inheritdoc />
    public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default)
    {
        UnsubscribeBatches.Enqueue(subscriptionIds.ToList());
        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public Task<string> SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default)
    {
        Interlocked.Increment(ref SingleSubscribeCalls);
        ValueCallback = callback;
        return Task.FromResult($"sub-{Interlocked.Increment(ref _nextId)}");
    }

    /// <inheritdoc />
    public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default)
        => Task.CompletedTask;

    /// <inheritdoc />
    public async Task<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default)
    {
        Interlocked.Increment(ref SingleReadCalls);
        if (HangReads)
            await Task.Delay(Timeout.Infinite, cancellationToken);
        return new ReadResult(true, new TagValue(SeedValue, QualityCode.Good, DateTimeOffset.UtcNow), null);
    }

    /// <inheritdoc />
    public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
        IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
    {
        var tags = tagPaths.ToList();
        ReadBatches.Enqueue(tags);
        if (HangReads)
            await Task.Delay(Timeout.Infinite, cancellationToken);

        return tags.ToDictionary(
            t => t,
            t => new ReadResult(true, new TagValue(SeedValue, QualityCode.Good, DateTimeOffset.UtcNow), null));
    }

    /// <inheritdoc />
    public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default)
        => Task.FromResult(new WriteResult(true, null));

    /// <inheritdoc />
    public Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(
        IDictionary<string, object?> values, CancellationToken cancellationToken = default)
        => Task.FromResult<IReadOnlyDictionary<string, WriteResult>>(
            values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null)));

    /// <inheritdoc />
    public Task<bool> WriteBatchAndWaitAsync(
        IDictionary<string, object?> values, string flagPath, object? flagValue, string responsePath,
        object? responseValue, TimeSpan timeout, CancellationToken cancellationToken = default)
        => Task.FromResult(true);

    /// <inheritdoc />
    public Task<string> SubscribeAlarmsAsync(
        string sourceReference, string? conditionFilter, AlarmTransitionCallback callback,
        CancellationToken cancellationToken = default)
    {
        AlarmCallback = callback;
        return Task.FromResult($"alarm-{Interlocked.Increment(ref _nextId)}");
    }

    /// <inheritdoc />
    public Task UnsubscribeAlarmsAsync(string subscriptionId, CancellationToken cancellationToken = default)
        => Task.CompletedTask;

    /// <inheritdoc />
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
