using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.SignalR.Client;

namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;

/// <summary>
/// Client-side helper that builds a <see cref="HubConnection"/> targeted at a
/// dashboard hub. Mints a fresh data-protected bearer token via
/// <see cref="HubTokenService"/> on every (re)connect so the connection
/// authenticates against <see cref="DashboardAuthenticationDefaults.HubAuthenticationScheme"/>
/// without needing to forward the browser's HttpOnly cookie.
/// </summary>
public sealed class DashboardHubConnectionFactory(
    NavigationManager navigation,
    HubTokenService tokens,
    AuthenticationStateProvider authState)
{
    /// <summary>Creates a new hub connection to the specified hub path.</summary>
    /// <param name="hubPath">The relative hub path (e.g., "/hubs/snapshot").</param>
    /// <returns>A configured hub connection with automatic reconnection and token authentication.</returns>
    public HubConnection Create(string hubPath)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(hubPath);

        Uri hubUrl = navigation.ToAbsoluteUri(hubPath);
        return new HubConnectionBuilder()
            .WithUrl(hubUrl, options =>
            {
                options.AccessTokenProvider = async () =>
                {
                    AuthenticationState state = await authState.GetAuthenticationStateAsync().ConfigureAwait(false);
                    return tokens.Issue(state.User);
                };
            })
            .WithAutomaticReconnect()
            .Build();
    }
}
