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
{
    /// <summary>
    /// Gets the gateway client options.
    /// </summary>
    public MxGatewayClientOptions Options { get; } = options;

    /// <summary>
    /// Gets the raw gRPC client; always null for the fake.
    /// </summary>
    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();

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

    /// <summary>
    /// Records the request and either throws a queued exception or returns the configured reply.
    /// </summary>
    /// <param name="request">The TestConnectionRequest to process.</param>
    /// <param name="callOptions">Call options specifying RPC behavior.</param>
    public Task<TestConnectionReply> TestConnectionAsync(
        TestConnectionRequest request,
        CallOptions callOptions)
    {
        TestConnectionCalls.Add((request, callOptions));
        if (TestConnectionExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        return Task.FromResult(TestConnectionReply);
    }

    /// <summary>
    /// Records the request and either throws a queued exception or returns the configured reply.
    /// </summary>
    /// <param name="request">The GetLastDeployTimeRequest to process.</param>
    /// <param name="callOptions">Call options specifying RPC behavior.</param>
    public Task<GetLastDeployTimeReply> GetLastDeployTimeAsync(
        GetLastDeployTimeRequest request,
        CallOptions callOptions)
    {
        GetLastDeployTimeCalls.Add((request, callOptions));
        if (GetLastDeployTimeExceptions.TryDequeue(out Exception? exception))
        {
            throw exception;
        }

        return Task.FromResult(GetLastDeployTimeReply);
    }

    /// <summary>
    /// Records the request and either throws a queued exception or returns the configured reply.
    /// </summary>
    /// <param name="request">The DiscoverHierarchyRequest to process.</param>
    /// <param name="callOptions">Call options specifying RPC behavior.</param>
    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>
    /// 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; }

    /// <summary>
    /// Records the request and streams events, checking for queued exceptions and calling WatchDeployEventsBeforeYield before each event.
    /// </summary>
    /// <param name="request">The WatchDeployEventsRequest to process.</param>
    /// <param name="callOptions">Call options specifying RPC behavior.</param>
    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;
        }
    }
}
