import notEmpty from '@inject/shared/utils/notEmpty'
import { useEffect } from 'react'
import { useGetExercises } from '../queries/GetExercises.generated'
import type { Exercises } from '../subscriptions/Exercises.generated'
import { ExercisesDocument } from '../subscriptions/Exercises.generated'

const useExercisesSubscription = () => {
  const query = useGetExercises()

  const { subscribeToMore } = query
  useEffect(
    () =>
      subscribeToMore({
        document: ExercisesDocument,
        updateQuery: (prev, { subscriptionData }) => {
          // Codegen implicitly typecasts subscriptionData to the parent query type, this is not desired
          const retypedData = subscriptionData.data as unknown as Exercises
          if (
            !retypedData ||
            !retypedData.exercisesSubscription ||
            !retypedData.exercisesSubscription.exercise ||
            !retypedData.exercisesSubscription.eventType
          )
            return prev
          if (!prev.exercises) return prev

          const newExercise = retypedData.exercisesSubscription.exercise
          const eventType = retypedData.exercisesSubscription.eventType

          const oldExercises = (prev.exercises || []).filter(notEmpty)

          if (eventType === 'CREATE') {
            return {
              ...prev,
              exercises: [...oldExercises, newExercise],
            }
          } else if (eventType === 'DELETE') {
            return {
              ...prev,
              exercises: oldExercises.filter(
                exercise => exercise.id !== newExercise.id
              ),
            }
          }
          // eventType === 'MODIFY'
          return {
            ...prev,
            exercises: oldExercises.map(exercise =>
              exercise.id === newExercise.id ? newExercise : exercise
            ),
          }
        },
      }),
    [subscribeToMore]
  )

  return query
}

export default useExercisesSubscription
