/**
 * 文件职责：订单大厅数据加载动作。
 */
import type { Ref } from 'vue';

import type { OrderHallPageState, OrderHallStatsState } from '../../types';

import type { OrderBoardCard } from '#/api/order-hall';
import type { StoreListItemDto } from '#/api/store';

import {
  getOrderBoardApi,
  getOrderBoardStatsApi,
  getPendingSinceApi,
} from '#/api/order-hall';
import { getStoreListApi } from '#/api/store';

import { mapStoreOptions } from '../../types';

/** 数据加载动作选项。 */
interface DataActionsOptions {
  state: OrderHallPageState;
  statsRef: Ref<OrderHallStatsState>;
}

/** 创建数据加载动作。 */
export function createDataActions(options: DataActionsOptions) {
  const { state, statsRef } = options;

  // 1. 加载门店并初始化默认门店
  async function loadStores(): Promise<void> {
    state.isStoreLoading = true;
    try {
      const result = await getStoreListApi({ page: 1, pageSize: 200 });
      const stores = result.items ?? ([] as StoreListItemDto[]);
      state.storeOptions = mapStoreOptions(stores);

      if (stores.length === 0) {
        state.selectedStoreId = '';
        state.pendingCards = [];
        state.makingCards = [];
        state.deliveringCards = [];
        state.completedCards = [];
        statsRef.value = {
          todayTotal: 0,
          pendingCount: 0,
          makingCount: 0,
          deliveringCount: 0,
          completedCount: 0,
        };
        return;
      }

      const matched = stores.some((item) => item.id === state.selectedStoreId);
      if (!matched) {
        state.selectedStoreId = stores[0]?.id ?? '';
      }
    } finally {
      state.isStoreLoading = false;
    }
  }

  // 2. 加载完整看板数据
  async function loadFullBoard(): Promise<void> {
    if (!state.selectedStoreId) return;
    state.isLoading = true;
    try {
      const result = await getOrderBoardApi({
        storeId: state.selectedStoreId,
      });
      state.pendingCards = result.pending;
      state.makingCards = result.making;
      state.deliveringCards = result.delivering;
      state.completedCards = result.completed;
    } finally {
      state.isLoading = false;
    }
  }

  // 3. 加载统计数据
  async function loadStats(): Promise<void> {
    if (!state.selectedStoreId) return;
    const result = await getOrderBoardStatsApi({
      storeId: state.selectedStoreId,
    });
    statsRef.value = result;
  }

  // 4. 重连补偿拉取
  async function catchUpSince(since: Date): Promise<OrderBoardCard[]> {
    if (!state.selectedStoreId) return [];
    return getPendingSinceApi({
      storeId: state.selectedStoreId,
      since: since.toISOString(),
    });
  }

  return { loadStores, loadFullBoard, loadStats, catchUpSince };
}
