using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

namespace ColaFlow.API.Hubs;

[Authorize] // All Hubs require authentication
public abstract class BaseHub : Hub
{
    protected Guid GetCurrentUserId()
    {
        var userIdClaim = Context.User?.FindFirst("sub")
            ?? Context.User?.FindFirst("user_id");

        if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
        {
            throw new UnauthorizedAccessException("User ID not found in token");
        }

        return userId;
    }

    protected Guid GetCurrentTenantId()
    {
        var tenantIdClaim = Context.User?.FindFirst("tenant_id");

        if (tenantIdClaim == null || !Guid.TryParse(tenantIdClaim.Value, out var tenantId))
        {
            throw new UnauthorizedAccessException("Tenant ID not found in token");
        }

        return tenantId;
    }

    protected string GetTenantGroupName(Guid tenantId)
    {
        return $"tenant-{tenantId}";
    }

    public override async Task OnConnectedAsync()
    {
        try
        {
            var tenantId = GetCurrentTenantId();
            var userId = GetCurrentUserId();

            // Automatically join tenant group (tenant isolation)
            await Groups.AddToGroupAsync(Context.ConnectionId, GetTenantGroupName(tenantId));

            // Log connection
            Console.WriteLine($"User {userId} from tenant {tenantId} connected. ConnectionId: {Context.ConnectionId}");

            await base.OnConnectedAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Connection error: {ex.Message}");
            Context.Abort();
        }
    }

    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        var tenantId = GetCurrentTenantId();
        var userId = GetCurrentUserId();

        Console.WriteLine($"User {userId} from tenant {tenantId} disconnected. Reason: {exception?.Message ?? "Normal"}");

        await base.OnDisconnectedAsync(exception);
    }
}
