using Microsoft.AspNetCore.SignalR;
using timetracker.Shared;

namespace timetracker.Data;

public class UserNotificationService : IUserNotificationService
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public event Func<Task>? OnUsersChanged;
    public event Func<int, Task>? OnUserDeleted;

    public UserNotificationService(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task NotifyUsersChangedAsync()
    {
        // Broadcast via SignalR to all clients
        await _hubContext.Clients.All.SendAsync("UsersChanged");
        
        // Also trigger locally if there are server-side subscribers
        if (OnUsersChanged != null)
            await OnUsersChanged.Invoke();
    }

    public async Task NotifyUserDeletedAsync(int userId)
    {
        // Broadcast via SignalR to all clients
        await _hubContext.Clients.All.SendAsync("UserDeleted", userId);
        
        // Also trigger locally if there are server-side subscribers
        if (OnUserDeleted != null)
            await OnUserDeleted.Invoke(userId);
    }
}
