/**
 * 每周营业时间保存动作。
 */
import type { Ref } from 'vue';

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

import { message } from 'ant-design-vue';

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

interface CreateWeeklyActionsOptions {
  isWeeklySubmitting: Ref<boolean>;
  loadStoreHours: (storeId: string) => Promise<void>;
  normalizeWeeklyHours: (source: DayHoursDto[]) => DayHoursDto[];
  selectedStoreId: Ref<string>;
}

export function createWeeklyActions(options: CreateWeeklyActionsOptions) {
  // 保存后刷新当前门店数据，保证页面展示与服务端一致。
  async function persistWeeklyHours(
    nextWeekly: DayHoursDto[],
    successText: string,
  ) {
    if (!options.selectedStoreId.value) return false;

    options.isWeeklySubmitting.value = true;
    try {
      await saveWeeklyHoursApi({
        storeId: options.selectedStoreId.value,
        weeklyHours: options.normalizeWeeklyHours(nextWeekly),
      });
      message.success(successText);
      await options.loadStoreHours(options.selectedStoreId.value);
      return true;
    } catch (error) {
      console.error(error);
      return false;
    } finally {
      options.isWeeklySubmitting.value = false;
    }
  }

  return {
    persistWeeklyHours,
  };
}
