using System.Collections.Concurrent;
using System.Security.Claims;
using Mbproxy.Admin;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR;

namespace Mbproxy.Tests.Admin;

/// <summary>
/// Minimal hand-written test doubles for the SignalR surface <see cref="StatusHub"/>
/// and <see cref="StatusBroadcaster"/> touch. The project carries no mocking framework,
/// so these record just enough to assert behaviour.
/// </summary>
internal sealed class FakeHubCallerContext : HubCallerContext
{
    public FakeHubCallerContext(string connectionId) => ConnectionId = connectionId;

    public override string ConnectionId { get; }
    public override string? UserIdentifier => null;
    public override ClaimsPrincipal? User => null;
    public override IDictionary<object, object?> Items { get; } = new Dictionary<object, object?>();
    public override IFeatureCollection Features { get; } = new FeatureCollection();
    public override CancellationToken ConnectionAborted => CancellationToken.None;
    public override void Abort() { }
}

/// <summary>Records every group join/leave so tests can assert membership changes.</summary>
internal sealed class FakeGroupManager : IGroupManager
{
    public List<(string ConnectionId, string Group)> Added { get; } = [];
    public List<(string ConnectionId, string Group)> Removed { get; } = [];

    public Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
    {
        Added.Add((connectionId, groupName));
        return Task.CompletedTask;
    }

    public Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default)
    {
        Removed.Add((connectionId, groupName));
        return Task.CompletedTask;
    }
}

/// <summary>Records every push so <see cref="StatusBroadcaster"/> tests can assert routing.</summary>
internal sealed class FakeStatusPushSink : IStatusPushSink
{
    private readonly ConcurrentBag<StatusResponse> _fleet = [];
    private readonly ConcurrentBag<(string Plc, PlcDetailResponse Detail)> _plc = [];

    public IReadOnlyCollection<StatusResponse> FleetPushes => _fleet;
    public IReadOnlyCollection<(string Plc, PlcDetailResponse Detail)> PlcPushes => _plc;

    public Task PushFleetAsync(StatusResponse snapshot, CancellationToken ct)
    {
        _fleet.Add(snapshot);
        return Task.CompletedTask;
    }

    public Task PushPlcAsync(string plcName, PlcDetailResponse detail, CancellationToken ct)
    {
        _plc.Add((plcName, detail));
        return Task.CompletedTask;
    }
}
