using System.Threading.Channels;
using RioJoy.Core.Serial;

namespace RioJoy.Core.Tests.Serial;

/// <summary>
/// In-memory <see cref="IRioTransport"/> for driving <see cref="RioSerialLink"/>
/// in tests: enqueue inbound chunks, inspect outbound writes.
/// </summary>
internal sealed class FakeTransport : IRioTransport
{
    private readonly Channel<byte[]> _incoming = Channel.CreateUnbounded<byte[]>();
    private readonly Channel<byte[]> _writes = Channel.CreateUnbounded<byte[]>();

    public string Description => "fake";

    /// <summary>Outbound writes, in order. Each call to WriteAsync yields one item.</summary>
    public ChannelReader<byte[]> Writes => _writes.Reader;

    /// <summary>Queue an inbound chunk for the receive loop to read.</summary>
    public void Enqueue(params byte[] data) => _incoming.Writer.TryWrite(data);

    /// <summary>Signal that no more inbound data will arrive (transport closed).</summary>
    public void CompleteIncoming() => _incoming.Writer.TryComplete();

    public async Task<int> ReadAsync(byte[] buffer, CancellationToken cancellationToken)
    {
        while (await _incoming.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
        {
            if (_incoming.Reader.TryRead(out byte[]? chunk))
            {
                Array.Copy(chunk, buffer, chunk.Length);
                return chunk.Length;
            }
        }

        return 0; // completed
    }

    public Task WriteAsync(byte[] data, CancellationToken cancellationToken)
    {
        _writes.Writer.TryWrite((byte[])data.Clone());
        return Task.CompletedTask;
    }

    /// <summary>Read the next outbound write, failing if none arrives in time.</summary>
    public async Task<byte[]> NextWriteAsync(TimeSpan? timeout = null)
    {
        using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5));
        return await _writes.Reader.ReadAsync(cts.Token).ConfigureAwait(false);
    }

    public void Dispose() { }
}
