import type { MemberDetailDto } from '#/api/member';

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

import { getMemberDetailApi, saveMemberTagsApi } from '#/api/member';

interface DetailActionOptions {
  canManage: { value: boolean };
  detail: { value: MemberDetailDto | null };
  detailLoading: { value: boolean };
  detailOpen: { value: boolean };
  selectedStoreId: { value: string };
  tagSaving: { value: boolean };
}

/**
 * 文件职责：会员详情抽屉与标签编辑动作。
 */
export function createDetailActions(options: DetailActionOptions) {
  function setDetailOpen(value: boolean) {
    options.detailOpen.value = value;
    if (!value) {
      options.detail.value = null;
    }
  }

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

    options.detailOpen.value = true;
    options.detail.value = null;
    options.detailLoading.value = true;
    try {
      options.detail.value = await getMemberDetailApi({
        storeId: options.selectedStoreId.value,
        memberId,
      });
    } finally {
      options.detailLoading.value = false;
    }
  }

  async function saveTags(tags: string[]) {
    if (!options.detail.value) {
      return;
    }

    if (!options.canManage.value) {
      message.warning('暂无标签编辑权限');
      return;
    }

    options.tagSaving.value = true;
    try {
      await saveMemberTagsApi({
        storeId: options.selectedStoreId.value,
        memberId: options.detail.value.memberId,
        tags,
      });
      options.detail.value = {
        ...options.detail.value,
        tags: [...tags],
      };
      message.success('标签已保存');
    } finally {
      options.tagSaving.value = false;
    }
  }

  return {
    openDetail,
    saveTags,
    setDetailOpen,
  };
}
