import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseChannels } from '@inject/graphql/queries'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useMemo } from 'react'

const useInstructorViewData = ({ exerciseId }: { exerciseId?: string }) => {
  const [
    { data: channelsData, fetching: channelsLoading, error: channelsError },
  ] = useTypedQuery({
    query: GetExerciseChannels,
    variables: { exerciseId: exerciseId || '' },
    pause: !exerciseId,
    requestPolicy: 'cache-first',
  })

  const channels = useMemo(
    () => channelsData?.exerciseChannels?.filter(notEmpty) || [],
    [channelsData?.exerciseChannels]
  )
  const emailsEnabled = useMemo(
    () => channels.some(channel => channel?.type === 'EMAIL'),
    [channels]
  )

  return {
    loading: channelsLoading,
    error: channelsError,
    emailsEnabled,
    channels,
  }
}

export default useInstructorViewData
