import type { Ref } from 'vue';

import type { CustomerMemberDetailDto } from '#/api/customer';

import { getCustomerMemberDetailApi } from '#/api/customer';

interface MemberActionOptions {
  detail: Ref<CustomerMemberDetailDto | null>;
  isMemberDrawerOpen: Ref<boolean>;
  isMemberLoading: Ref<boolean>;
  selectedStoreId: Ref<string>;
}

/**
 * 文件职责：客户分析页会员详情抽屉动作。
 */
export function createMemberActions(options: MemberActionOptions) {
  function setMemberDrawerOpen(value: boolean) {
    options.isMemberDrawerOpen.value = value;
    if (!value) {
      options.detail.value = null;
    }
  }

  async function openMember(customerKey: string) {
    if (!options.selectedStoreId.value || !customerKey) {
      return;
    }

    options.isMemberDrawerOpen.value = true;
    options.detail.value = null;
    options.isMemberLoading.value = true;
    try {
      options.detail.value = await getCustomerMemberDetailApi({
        storeId: options.selectedStoreId.value,
        customerKey,
      });
    } finally {
      options.isMemberLoading.value = false;
    }
  }

  return {
    openMember,
    setMemberDrawerOpen,
  };
}
