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

namespace TakeoutSaaS.TenantApi.Hubs;

/// <summary>
/// 订单大厅实时推送 Hub（只读，所有写操作走 HTTP API）。
/// </summary>
[Authorize]
public sealed class OrderBoardHub : Hub
{
    /// <summary>
    /// 连接建立时，自动加入门店 Group。
    /// </summary>
    public override async Task OnConnectedAsync()
    {
        // 1. 从 JWT claims 提取 tenant_id
        var tenantId = Context.User?.FindFirst("tenant_id")?.Value;
        var storeId = Context.GetHttpContext()?.Request.Query["storeId"].ToString();

        // 2. 加入门店 Group
        if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(storeId))
        {
            var group = $"store:{tenantId}:{storeId}";
            await Groups.AddToGroupAsync(Context.ConnectionId, group);
            Context.Items["currentGroup"] = group;
        }

        await base.OnConnectedAsync();
    }

    /// <summary>
    /// 连接断开时，移出 Group。
    /// </summary>
    public override async Task OnDisconnectedAsync(Exception? exception)
    {
        // 1. 移出当前 Group
        if (Context.Items.TryGetValue("currentGroup", out var groupObj) && groupObj is string group)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
        }

        await base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// 切换门店时调用，移出旧 Group 加入新 Group。
    /// </summary>
    public async Task JoinStore(string storeId)
    {
        // 1. 移出旧 Group
        if (Context.Items.TryGetValue("currentGroup", out var oldGroupObj) && oldGroupObj is string oldGroup)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, oldGroup);
        }

        // 2. 加入新 Group
        var tenantId = Context.User?.FindFirst("tenant_id")?.Value;
        if (!string.IsNullOrWhiteSpace(tenantId) && !string.IsNullOrWhiteSpace(storeId))
        {
            var newGroup = $"store:{tenantId}:{storeId}";
            await Groups.AddToGroupAsync(Context.ConnectionId, newGroup);
            Context.Items["currentGroup"] = newGroup;
        }
    }
}
