import type { CustomerDetailDto, CustomerProfileDto } from '#/api/customer';

import { getCustomerDetailApi, getCustomerProfileApi } from '#/api/customer';

interface DrawerActionOptions {
  detail: { value: CustomerDetailDto | null };
  isDetailDrawerOpen: { value: boolean };
  isDetailLoading: { value: boolean };
  isProfileDrawerOpen: { value: boolean };
  isProfileLoading: { value: boolean };
  profile: { value: CustomerProfileDto | null };
  selectedStoreId: { value: string };
}

/**
 * 文件职责：客户详情与画像抽屉动作。
 */
export function createDrawerActions(options: DrawerActionOptions) {
  function setDetailDrawerOpen(value: boolean) {
    options.isDetailDrawerOpen.value = value;
    if (!value) {
      options.detail.value = null;
      options.isProfileDrawerOpen.value = false;
      options.profile.value = null;
    }
  }

  function setProfileDrawerOpen(value: boolean) {
    options.isProfileDrawerOpen.value = value;
    if (!value) {
      options.profile.value = null;
    }
  }

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

    options.isDetailDrawerOpen.value = true;
    options.detail.value = null;
    options.isProfileDrawerOpen.value = false;
    options.profile.value = null;
    options.isDetailLoading.value = true;
    try {
      options.detail.value = await getCustomerDetailApi({
        storeId: options.selectedStoreId.value,
        customerKey,
      });
    } finally {
      options.isDetailLoading.value = false;
    }
  }

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

    options.isProfileDrawerOpen.value = true;
    options.profile.value = null;
    options.isProfileLoading.value = true;
    try {
      options.profile.value = await getCustomerProfileApi({
        storeId: options.selectedStoreId.value,
        customerKey,
      });
    } finally {
      options.isProfileLoading.value = false;
    }
  }

  return {
    openDetail,
    openProfile,
    setDetailDrawerOpen,
    setProfileDrawerOpen,
  };
}
