import type {
  NewOrderPayload,
  OrderHallPageState,
  OrderStatusChangedPayload,
  OrderUrgedPayload,
} from '../../types';

/**
 * 文件职责：订单大厅 SignalR 连接与事件处理。
 */
import type { OrderBoardCard } from '#/api/order-hall';

import { useSignalR } from '#/hooks/useSignalR';

/** SignalR 动作选项。 */
interface SignalRActionsOptions {
  state: OrderHallPageState;
  onNewOrder?: () => void;
  onUrge?: () => void;
  catchUpSince: (since: Date) => Promise<OrderBoardCard[]>;
  loadFullBoard: () => Promise<void>;
  loadStats: () => Promise<void>;
}

/** 创建 SignalR 动作。 */
export function createSignalRActions(options: SignalRActionsOptions) {
  const { state, onNewOrder, onUrge, catchUpSince, loadFullBoard, loadStats } =
    options;

  const { isConnected, connect, disconnect, on, invoke } = useSignalR({
    onReconnected: async (lastDisconnectedAt) => {
      // 1. 重连后补偿拉取
      const missed = await catchUpSince(lastDisconnectedAt);
      if (missed.length > 0) {
        await loadFullBoard();
        await loadStats();
      }
    },
  });

  // 2. 建立连接并订阅事件
  async function connectAndSubscribe(): Promise<void> {
    if (!state.selectedStoreId) return;

    await connect(state.selectedStoreId);

    // 3. 订阅新订单
    on<NewOrderPayload>('NewOrder', () => {
      loadFullBoard();
      loadStats();
      onNewOrder?.();
    });

    // 4. 订阅状态变更
    on<OrderStatusChangedPayload>('OrderStatusChanged', () => {
      loadFullBoard();
      loadStats();
    });

    // 5. 订阅催单
    on<OrderUrgedPayload>('OrderUrged', (data) => {
      // 标记对应卡片为催单状态
      const allCards = [
        ...state.pendingCards,
        ...state.makingCards,
        ...state.deliveringCards,
      ];
      const card = allCards.find((c) => c.orderNo === data.orderNo);
      if (card) {
        card.isUrged = true;
        card.urgeCount = data.urgeCount;
      }
      onUrge?.();
    });
  }

  // 6. 切换门店
  async function switchStore(storeId: string): Promise<void> {
    await (isConnected.value ? invoke('JoinStore', storeId) : connect(storeId));
  }

  return {
    isConnected,
    connectAndSubscribe,
    disconnect,
    switchStore,
  };
}
