using Grpc.Core;
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;

namespace ZB.MOM.WW.MxGateway.Client.Tests;

/// <summary>
/// Fake Galaxy Repository client transport for testing.
/// </summary>
internal sealed class FakeGalaxyRepositoryTransport(MxGatewayClientOptions options) : IGalaxyRepositoryClientTransport
{
    /// <inheritdoc />
    public MxGatewayClientOptions Options { get; } = options;

    /// <inheritdoc />
    public GalaxyRepository.GalaxyRepositoryClient? RawClient => null;

    /// <summary>
    /// Gets the list of TestConnection RPC calls made by the client.
    /// </summary>
    public List<(TestConnectionRequest Request, CallOptions CallOptions)> TestConnectionCalls { get; } = [];

    /// <summary>
    /// Gets the list of GetLastDeployTime RPC calls made by the client.
    /// </summary>
    public List<(GetLastDeployTimeRequest Request, CallOptions CallOptions)> GetLastDeployTimeCalls { get; } = [];

    /// <summary>
    /// Gets the list of DiscoverHierarchy RPC calls made by the client.
    /// </summary>
    public List<(DiscoverHierarchyRequest Request, CallOptions CallOptions)> DiscoverHierarchyCalls { get; } = [];

    /// <summary>
    /// Gets or sets the reply to return from TestConnection; defaults to successful response.
    /// </summary>
    public TestConnectionReply TestConnectionReply { get; set; } = new() { Ok = true };

    /// <summary>
    /// Gets or sets the reply to return from GetLastDeployTime; defaults to no deploy time present.
    /// </summary>
    public GetLastDeployTimeReply GetLastDeployTimeReply { get; set; } = new() { Present = false };

    /// <summary>
    /// Gets or sets the reply to return from DiscoverHierarchy; defaults to empty response.
    /// </summary>
    public DiscoverHierarchyReply DiscoverHierarchyReply { get; set; } = new();

    /// <summary>Gets the queue of discover hierarchy replies; dequeued in FIFO order.</summary>
    public Queue<DiscoverHierarchyReply> DiscoverHierarchyReplies { get; } = new();

    /// <summary>
    /// Gets the queue of exceptions to throw from TestConnection; dequeued in FIFO order.
    /// </summary>
    public Queue<Exception> TestConnectionExceptions { get; } = new();

    /// <summary>
    /// Gets the queue of exceptions to throw from GetLastDeployTime; dequeued in FIFO order.
    /// </summary>
    public Queue<Exception> GetLastDeployTimeExceptions { get; } = new();

    /// <summary>
    /// Gets the queue of exceptions to throw from DiscoverHierarchy; dequeued in FIFO order.
    /// </summary>
    public Queue<Exception> DiscoverHierarchyExceptions { get; } = new();

    /// <inheritdoc />
    public Task<TestConnectionReply> TestConnectionAsync(
        TestConnectionRequest request,
        CallOptions callOptions)
    {
        TestConnectionCalls.Add((request, callOptions));
        if (TestConnectionExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        return Task.FromResult(TestConnectionReply);
    }

    /// <inheritdoc />
    public Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
        GetLastDeployTimeRequest request,
        CallOptions callOptions)
    {
        GetLastDeployTimeCalls.Add((request, callOptions));
        if (GetLastDeployTimeExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        return Task.FromResult(GetLastDeployTimeReply);
    }

    /// <inheritdoc />
    public Task<DiscoverHierarchyReply> DiscoverHierarchyAsync(
        DiscoverHierarchyRequest request,
        CallOptions callOptions)
    {
        DiscoverHierarchyCalls.Add((request, callOptions));
        if (DiscoverHierarchyExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        return Task.FromResult(
            DiscoverHierarchyReplies.TryDequeue(out DiscoverHierarchyReply? reply)
                ? reply
                : DiscoverHierarchyReply);
    }

    /// <summary>Records BrowseChildren RPC calls made by the client.</summary>
    public List<(BrowseChildrenRequest Request, CallOptions CallOptions)> BrowseChildrenCalls { get; } = [];

    /// <summary>Default reply returned from BrowseChildren when the queue is empty.</summary>
    public BrowseChildrenReply BrowseChildrenReply { get; set; } = new();

    /// <summary>Queue of replies returned from BrowseChildren; dequeued in FIFO order.</summary>
    public Queue<BrowseChildrenReply> BrowseChildrenReplies { get; } = new();

    /// <summary>Queue of exceptions to throw from BrowseChildren; dequeued in FIFO order.</summary>
    public Queue<Exception> BrowseChildrenExceptions { get; } = new();

    /// <summary>
    /// Optional hook awaited inside BrowseChildren before the reply is produced. Lets a
    /// test hold an RPC mid-flight to exercise concurrent reads of the in-progress node.
    /// </summary>
    public Func<Task>? BrowseChildrenGate { get; set; }

    /// <inheritdoc />
    public async Task<BrowseChildrenReply> BrowseChildrenAsync(
        BrowseChildrenRequest request,
        CallOptions callOptions)
    {
        BrowseChildrenCalls.Add((request, callOptions));
        if (BrowseChildrenExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        if (BrowseChildrenGate is { } gate)
        {
            await gate().ConfigureAwait(false);
        }

        return BrowseChildrenReplies.TryDequeue(out BrowseChildrenReply? reply)
            ? reply
            : BrowseChildrenReply;
    }

    /// <summary>
    /// Gets the list of WatchDeployEvents RPC calls made by the client.
    /// </summary>
    public List<(WatchDeployEventsRequest Request, CallOptions CallOptions)> WatchDeployEventsCalls { get; } = [];

    /// <summary>
    /// Gets or sets the list of events to stream from WatchDeployEvents.
    /// </summary>
    public List<DeployEvent> WatchDeployEvents { get; } = [];

    /// <summary>
    /// Gets or sets the exception to throw from WatchDeployEvents, if any.
    /// </summary>
    public Exception? WatchDeployEventsException { get; set; }

    /// <summary>
    /// When set, awaited before each event yield so tests can observe cancellation
    /// mid-stream. Receives the call's cancellation token.
    /// </summary>
    public Func<CancellationToken, Task>? WatchDeployEventsBeforeYield { get; set; }

    /// <inheritdoc />
    public async IAsyncEnumerable<DeployEvent> WatchDeployEventsAsync(
        WatchDeployEventsRequest request,
        CallOptions callOptions)
    {
        WatchDeployEventsCalls.Add((request, callOptions));

        if (WatchDeployEventsException is not null)
        {
            throw WatchDeployEventsException;
        }

        foreach (DeployEvent deployEvent in WatchDeployEvents)
        {
            if (WatchDeployEventsBeforeYield is not null)
            {
                await WatchDeployEventsBeforeYield(callOptions.CancellationToken).ConfigureAwait(false);
            }

            callOptions.CancellationToken.ThrowIfCancellationRequested();
            yield return deployEvent;
        }
    }
}
