using Microsoft.AspNetCore.SignalR;
using ROLAC.API.Services;

namespace ROLAC.API.Hubs;

/// <summary>
/// Real-time hub backing the public Sunday attendance counter. Anonymous
/// (no [Authorize]) so volunteers can use it without logging in. Every
/// increment is broadcast to all connected clients so multiple people can
/// count the same Sunday together and see each other's changes instantly.
/// </summary>
public class AttendanceHub : Hub
{
    private readonly IMealAttendanceService _svc;

    public AttendanceHub(IMealAttendanceService svc) => _svc = svc;

    // Push the current counts to a client the moment it connects.
    public override async Task OnConnectedAsync()
    {
        var counts = await _svc.GetOrCreateAsync(_svc.ServiceDay);
        await Clients.Caller.SendAsync("ReceiveCounts", counts);
        await base.OnConnectedAsync();
    }

    // Apply a batched delta for one age group, then broadcast the new totals to everyone.
    public async Task Increment(string category, int delta)
    {
        var counts = await _svc.IncrementAsync(_svc.ServiceDay, category, delta);
        await Clients.All.SendAsync("ReceiveCounts", counts);
    }

    // Overwrite one age group with an absolute value, then broadcast the new totals to everyone.
    public async Task SetCount(string category, int value)
    {
        var counts = await _svc.SetAsync(_svc.ServiceDay, category, value);
        await Clients.All.SendAsync("ReceiveCounts", counts);
    }
}
