using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Meezi.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Meezi.API.Hubs;

[AllowAnonymous]
public class GuestOrderHub : Hub
{
    public static string OrderGroup(string orderId) => $"guest-order:{orderId}";

    public async Task JoinOrder(string orderId, string trackingToken)
    {
        if (string.IsNullOrWhiteSpace(orderId) || string.IsNullOrWhiteSpace(trackingToken))
            throw new HubException("Invalid order.");

        var db = Context.GetHttpContext()?.RequestServices.GetRequiredService<AppDbContext>();
        if (db is null)
            throw new HubException("Unavailable.");

        var valid = await db.Orders.AsNoTracking()
            .AnyAsync(o => o.Id == orderId && o.GuestTrackingToken == trackingToken);

        if (!valid)
            throw new HubException("Forbidden.");

        await Groups.AddToGroupAsync(Context.ConnectionId, OrderGroup(orderId));
    }

    public Task LeaveOrder(string orderId) =>
        Groups.RemoveFromGroupAsync(Context.ConnectionId, OrderGroup(orderId));
}
