import { useMutation, type MutationFunctionContext, type UseMutationOptions } from '@tanstack/react-query'
import { addNotification } from '../model/notification'
import { getApiErrorMessage } from './get-api-error-message'

type MutationWithToastOptions<TData, TError, TVariables, TOnMutateResult> = UseMutationOptions<
  TData,
  TError,
  TVariables,
  TOnMutateResult
> & {
  successMessage?: string
}

export function useMutationWithToast<TData = unknown, TError = unknown, TVariables = void, TOnMutateResult = unknown>(
  options: MutationWithToastOptions<TData, TError, TVariables, TOnMutateResult>,
) {
  const { successMessage, onSuccess, onError, ...mutationOptions } = options

  return useMutation({
    ...mutationOptions,
    onSuccess: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult, mutationContext: MutationFunctionContext) => {
      if (successMessage) {
        addNotification({ type: 'success', message: successMessage })
      }
      onSuccess?.(data, variables, onMutateResult, mutationContext)
    },
    onError: (error: TError, variables: TVariables, onMutateResult: TOnMutateResult | undefined, mutationContext: MutationFunctionContext) => {
      addNotification({ type: 'error', message: getApiErrorMessage(error) })
      onError?.(error, variables, onMutateResult, mutationContext)
    },
  })
}
