import ExerciseContext from '@/analyst/ExerciseContext'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetAnalyticsEmailThreads } from '@inject/graphql/queries'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useContext, useMemo } from 'react'

const useEmailThreads = () => {
  const { exercise } = useContext(ExerciseContext)

  const [{ data: emailThreadsData }] = useTypedQuery({
    query: GetAnalyticsEmailThreads,
    variables: {
      exerciseId: exercise.id,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  return emailThreadsData && emailThreadsData.analyticsEmailThreads
    ? emailThreadsData.analyticsEmailThreads.filter(notEmpty)
    : []
}

export default useEmailThreads
