using Microsoft.AspNetCore.SignalR;

namespace Apollinare.API.Hubs;

/// <summary>
/// Hub SignalR per la sincronizzazione in tempo reale dei dati tra client
/// </summary>
public class DataHub : Hub
{
    /// <summary>
    /// Notifica tutti i client che un'entità è stata modificata
    /// </summary>
    public async Task NotifyDataChanged(string entityType, string action, object? data = null)
    {
        try
        {
            await Clients.Others.SendAsync("DataChanged", entityType, action, data);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[DataHub] Error in NotifyDataChanged: {ex.Message}");
        }
    }

    public override async Task OnConnectedAsync()
    {
        try
        {
            Console.WriteLine($"[DataHub] Client connecting: {Context.ConnectionId}");
            await base.OnConnectedAsync();
            Console.WriteLine($"[DataHub] Client connected: {Context.ConnectionId}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[DataHub] Error in OnConnectedAsync: {ex.Message}");
            throw;
        }
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        try
        {
            if (exception != null)
            {
                Console.WriteLine($"[DataHub] Client disconnected with error: {Context.ConnectionId} - {exception.Message}");
            }
            else
            {
                Console.WriteLine($"[DataHub] Client disconnected: {Context.ConnectionId}");
            }
            await base.OnDisconnectedAsync(exception);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[DataHub] Error in OnDisconnectedAsync: {ex.Message}");
            throw;
        }
    }
}

/// <summary>
/// Servizio per inviare notifiche dal backend ai client
/// </summary>
public class DataNotificationService
{
    private readonly IHubContext<DataHub> _hubContext;

    public DataNotificationService(IHubContext<DataHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task NotifyCreated<T>(string entityType, T entity)
    {
        await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "created", entity);
    }

    public async Task NotifyUpdated<T>(string entityType, T entity)
    {
        await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "updated", entity);
    }

    public async Task NotifyDeleted(string entityType, int id)
    {
        await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "deleted", new { id });
    }

    public async Task NotifyBulkChange(string entityType)
    {
        await _hubContext.Clients.All.SendAsync("DataChanged", entityType, "bulk", null);
    }
}
