import { useMutation, useQueryClient, type QueryKey } from '@tanstack/react-query';
import { message } from '../ui/app-message';
import { getErrorMessage } from '../utils/error';

interface UseApiMutationOptions<TData, TVars> {
  /** 成功后自动失效的查询 key（触发列表/详情刷新） */
  invalidate?: QueryKey[];
  /** 成功后回调（例如关闭弹窗） */
  onSuccess?: (data: TData, vars: TVars) => void;
  /** 失败回调；默认统一用 getErrorMessage 弹错误提示 */
  onError?: (error: unknown) => void;
}

/**
 * useMutation 的轻量封装：统一错误提示 + 成功后 invalidateQueries，
 * 消除手写 `await api.xxx(); await fetchData();` 样板。
 */
export function useApiMutation<TData = unknown, TVars = void>(
  mutationFn: (vars: TVars) => Promise<TData>,
  options: UseApiMutationOptions<TData, TVars> = {},
) {
  const queryClient = useQueryClient();
  return useMutation<TData, Error, TVars>({
    mutationFn,
    onSuccess: (data, vars) => {
      for (const key of options.invalidate ?? []) {
        void queryClient.invalidateQueries({ queryKey: key });
      }
      options.onSuccess?.(data, vars);
    },
    onError: (error) => {
      if (options.onError) {
        options.onError(error);
      } else {
        message.error(getErrorMessage(error));
      }
    },
  });
}
