import notEmpty from '@inject/shared/utils/notEmpty'
import { useEffect } from 'react'
import { useGetAnalyticsEmailThreadsSuspenseQuery } from '../queries/GetAnalyticsEmailThreads.generated'
import type { ExerciseEmailThreads } from '../subscriptions/AnalyticsEmailThread.generated'
import { ExerciseEmailThreadsDocument } from '../subscriptions/AnalyticsEmailThread.generated'

const useAnalyticsEmailThreadsSubscription = (exerciseId: string) => {
  const query = useGetAnalyticsEmailThreadsSuspenseQuery({
    variables: { exerciseId },
  })

  const { subscribeToMore } = query
  useEffect(
    () =>
      subscribeToMore({
        document: ExerciseEmailThreadsDocument,
        variables: { exerciseId },
        updateQuery: (prev, { subscriptionData }) => {
          // Codegen implicitly typecasts subscriptionData to the parent query type, this is not desired
          const retypedData =
            subscriptionData.data as unknown as ExerciseEmailThreads
          if (
            !retypedData ||
            !retypedData.analyticsEmailThreadSubscription ||
            !retypedData.analyticsEmailThreadSubscription.emailThread
          )
            return prev

          const newEmailThread =
            retypedData.analyticsEmailThreadSubscription.emailThread
          const oldEmailThreads = (prev.analyticsEmailThreads || [])
            .filter(notEmpty)
            .filter(emailThread => emailThread.id !== newEmailThread.id)

          return {
            ...prev,
            analyticsEmailThreads: [...oldEmailThreads, newEmailThread],
          }
        },
      }),
    [exerciseId, subscribeToMore]
  )

  return query
}

export default useAnalyticsEmailThreadsSubscription
