import { useMutation, useQueryClient } from "@tanstack/react-query";

export function useAdminMutation(mutationFn, options = {}) {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (args) => mutationFn(...args),
    onSuccess: async (data, variables, context) => {
      if (options.invalidateQueries) {
        const keys = Array.isArray(options.invalidateQueries[0])
          ? options.invalidateQueries
          : [options.invalidateQueries];
        await Promise.all(keys.map((queryKey) => queryClient.invalidateQueries({ queryKey })));
      }
      if (options.onSuccess) {
        await options.onSuccess(data, variables, context);
      }
    }
  });

  return {
    error: mutation.error ? mutation.error.message || "操作失败" : "",
    loading: mutation.isPending,
    mutate: (...args) => mutation.mutateAsync(args)
  };
}
