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

namespace timetracker.Client.Services;

public class UserNotificationService : IUserNotificationService, IAsyncDisposable
{
    private readonly HubConnection _hubConnection;

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

    public UserNotificationService(NavigationManager navigationManager)
    {
        _hubConnection = new HubConnectionBuilder()
            .WithUrl(navigationManager.ToAbsoluteUri("/hubs/notifications"))
            .WithAutomaticReconnect()
            .Build();

        _hubConnection.On("UsersChanged", async () =>
        {
            if (OnUsersChanged != null)
                await OnUsersChanged.Invoke();
        });

        _hubConnection.On<int>("UserDeleted", async (userId) =>
        {
            if (OnUserDeleted != null)
                await OnUserDeleted.Invoke(userId);
        });

        // Start connection asynchronously
        _ = StartHubConnectionAsync();
    }

    private async Task StartHubConnectionAsync()
    {
        try
        {
            await _hubConnection.StartAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"SignalR Connection Error: {ex.Message}");
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (_hubConnection != null)
        {
            await _hubConnection.DisposeAsync();
        }
    }
}
