/**
 * 门店与营业时间数据加载动作：
 * - 拉取门店列表
 * - 按门店拉取营业时间
 */
import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
import type { DayHoursDto, HolidayDto } from '#/api/store-hours';

import { getStoreListApi } from '#/api/store';
import { getStoreHoursApi } from '#/api/store-hours';

interface CreateDataActionsOptions {
  holidays: Ref<HolidayDto[]>;
  isHoursLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  normalizeHolidays: (source: HolidayDto[]) => HolidayDto[];
  normalizeWeeklyHours: (source: DayHoursDto[]) => DayHoursDto[];
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
  weeklyHours: Ref<DayHoursDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  // 1. 加载指定门店的营业时间配置。
  async function loadStoreHours(storeId: string) {
    options.isHoursLoading.value = true;
    try {
      const currentStoreId = storeId;
      const result = await getStoreHoursApi(storeId);
      if (options.selectedStoreId.value !== currentStoreId) return;

      options.weeklyHours.value = options.normalizeWeeklyHours(
        result.weeklyHours ?? [],
      );
      options.holidays.value = options.normalizeHolidays(result.holidays ?? []);
    } catch (error) {
      console.error(error);
    } finally {
      options.isHoursLoading.value = false;
    }
  }

  // 2. 加载门店列表并处理默认选中逻辑。
  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({
        keyword: undefined,
        businessStatus: undefined,
        auditStatus: undefined,
        serviceType: undefined,
        page: 1,
        pageSize: 200,
      });
      options.stores.value = result.items ?? [];

      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        options.weeklyHours.value = options.normalizeWeeklyHours([]);
        options.holidays.value = [];
        return;
      }

      const hasSelected = options.stores.value.some(
        (store) => store.id === options.selectedStoreId.value,
      );

      if (!hasSelected) {
        const firstStore = options.stores.value[0];
        if (firstStore) {
          options.selectedStoreId.value = firstStore.id;
        }
      } else if (options.selectedStoreId.value) {
        await loadStoreHours(options.selectedStoreId.value);
      }
    } catch (error) {
      console.error(error);
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  return {
    loadStoreHours,
    loadStores,
  };
}
