import { useCallback } from "react"
import {
  type ApolloCache,
  type ApolloError,
  type DefaultContext,
  type MutationHookOptions,
  type OperationVariables,
  type TypedDocumentNode,
  useMutation,
} from "@apollo/client"
import toast from "react-hot-toast"

function onError(error: ApolloError) {
  toast.error(error.message)
}

/**
 * Simplified version of `useMutation`.
 */
export function useMutate<
  TData = any,
  TVariables = OperationVariables,
  TContext = DefaultContext,
  TCache extends ApolloCache<any> = ApolloCache<any>,
>(
  mutation: TypedDocumentNode<TData, TVariables>,
  options?: MutationHookOptions<TData, TVariables, TContext, TCache>,
) {
  const [mutate] = useMutation<TData, TVariables, TContext, TCache>(mutation, options)
  return useCallback((variables: TVariables) => mutate({ variables, onError }), [mutate])
}
