import type { Ref } from 'vue';

import type { ProductLabelTableRowViewModel } from '#/views/product/labels/types';

/**
 * 文件职责：标签行操作动作。
 * 1. 处理标签删除。
 * 2. 处理标签启用与停用。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeProductLabelStatusApi,
  deleteProductLabelApi,
} from '#/api/product';

interface CreateLabelActionsOptions {
  loadLabels: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createLabelActions(options: CreateLabelActionsOptions) {
  async function updateStatus(
    item: ProductLabelTableRowViewModel,
    status: 'disabled' | 'enabled',
    successMessage: string,
  ) {
    if (!options.selectedStoreId.value) return;
    try {
      await changeProductLabelStatusApi({
        storeId: options.selectedStoreId.value,
        labelId: item.id,
        status,
      });
      message.success(successMessage);
      await options.loadLabels();
    } catch (error) {
      console.error(error);
      message.error('标签状态更新失败');
    }
  }

  async function enableLabel(item: ProductLabelTableRowViewModel) {
    await updateStatus(item, 'enabled', '标签已启用');
  }

  async function disableLabel(item: ProductLabelTableRowViewModel) {
    await updateStatus(item, 'disabled', '标签已停用');
  }

  function removeLabel(item: ProductLabelTableRowViewModel) {
    if (!options.selectedStoreId.value) return;
    Modal.confirm({
      title: `确认删除标签「${item.name}」吗？`,
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        await deleteProductLabelApi({
          storeId: options.selectedStoreId.value,
          labelId: item.id,
        });
        message.success('标签已删除');
        await options.loadLabels();
      },
    });
  }

  return {
    disableLabel,
    enableLabel,
    removeLabel,
  };
}
