using Microsoft.AspNetCore.SignalR;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Server.Alarms;

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

/// <summary>
/// Background service that subscribes to
/// <see cref="IGatewayAlarmService.StreamAsync"/> (no filter) and re-broadcasts
/// every <see cref="AlarmFeedMessage"/> to every <see cref="AlarmsHub"/>
/// client. The hub itself is session-less; clients filter / route messages
/// in the browser.
/// </summary>
public sealed class AlarmsHubPublisher(
    IGatewayAlarmService alarmService,
    IHubContext<AlarmsHub> hubContext,
    ILogger<AlarmsHubPublisher> logger) : BackgroundService
{
    /// <inheritdoc />
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Loop forever — when StreamAsync completes (monitor restart, etc.)
        // reopen the subscription. The hosted-service lifetime ends only
        // when the host stops.
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await foreach (AlarmFeedMessage message in alarmService
                    .StreamAsync(alarmFilterPrefix: null, stoppingToken)
                    .ConfigureAwait(false))
                {
                    if (stoppingToken.IsCancellationRequested)
                    {
                        break;
                    }

                    try
                    {
                        await hubContext.Clients
                            .Group(AlarmsHub.AllAlarmsGroup)
                            .SendAsync(AlarmsHub.AlarmMessage, message, stoppingToken)
                            .ConfigureAwait(false);
                    }
                    catch (Exception ex) when (ex is not OperationCanceledException)
                    {
                        logger.LogWarning(ex, "Alarm broadcast failed; continuing.");
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                logger.LogWarning(ex, "Alarm subscription faulted; reconnecting in 5s.");
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    return;
                }
            }
        }
    }
}
