using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Hubs;

/// <summary>
///     SignalR hub clients subscribe to for live driver-health updates. Clients invoke
///     <see cref="JoinDriver"/> once per page-load to receive the current snapshot + future
///     state transitions for one driver instance.
/// </summary>
[Authorize]
public sealed class DriverStatusHub : Hub
{
    public const string Endpoint = "/hubs/driverstatus";

    /// <summary>SignalR method name used to push <see cref="DriverHealthChanged"/> snapshots to clients.</summary>
    public const string MethodName = "status";

    private readonly IDriverStatusSnapshotStore _store;

    /// <summary>Initializes a new instance of <see cref="DriverStatusHub"/>.</summary>
    /// <param name="store">In-memory snapshot store supplying current state on join.</param>
    public DriverStatusHub(IDriverStatusSnapshotStore store) => _store = store;

    /// <summary>
    ///     Adds the calling connection to a per-driver-instance group. Immediately replies with
    ///     the current snapshot from the in-memory store so the client renders state without
    ///     waiting for the next change event.
    /// </summary>
    /// <param name="driverInstanceId">Identifier of the driver instance to join.</param>
    /// <returns>A task that represents the asynchronous operation.</returns>
    public async Task JoinDriver(string driverInstanceId)
    {
        var groupName = GroupName(driverInstanceId);
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

        if (_store.TryGet(driverInstanceId, out var snapshot))
        {
            await Clients.Caller.SendAsync(MethodName, snapshot);
        }
    }

    /// <summary>Builds the SignalR group name for a given driver instance.</summary>
    /// <param name="driverInstanceId">Identifier of the driver instance.</param>
    /// <returns>The SignalR group name for the driver instance.</returns>
    public static string GroupName(string driverInstanceId) => $"driver:{driverInstanceId}";
}
