import type { TadaDocumentNode } from 'gql.tada'
import { useCallback } from 'react'
import type { AnyVariables, UseMutationResponse } from 'urql'
import { useMutation } from 'urql'
import { useLoopStatus } from './useExerciseLoopStatusSubscription'

export default function useBlockableMutation<
  Result,
  Variables extends AnyVariables = AnyVariables,
>(
  query: TadaDocumentNode<Result, Variables>
): [boolean, ...UseMutationResponse<Result, Variables>] {
  const { running } = useLoopStatus()

  const [mutateData, mutate] = useMutation<Result, Variables>(query)
  const wrappedMutate = useCallback(
    (...props: Parameters<typeof mutate>) => {
      if (running) {
        return mutate(...props)
      }
      throw Error(
        'Mutation is not allowed to execute, please take care of this in the UI :)'
      )
    },
    [running, mutate]
  )

  return [running, mutateData, wrappedMutate]
}
