import type { ResultOf, VariablesOf } from 'gql.tada'
import { useEffect, useMemo } from 'react'
import { useQuery } from 'urql'
import { GetExerciseQuestionnaires } from '../../queries'
import { teamQuestionnaireState } from '../../subscriptions'
import { useClient } from '../../urql/client'
import { useGenericActionLogEvent } from './utils'

const useQuestionnaireSubscriptionInstructor = ({
  exerciseId,
  teamIds,
}: {
  exerciseId: string
  teamIds: string[]
}) => {
  const client = useClient()
  const [, refetch] = useQuery({
    query: GetExerciseQuestionnaires,
    variables: {
      exerciseId,
    },
    pause: true,
    requestPolicy: 'cache-and-network',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  useEffect(() => {
    if (!exerciseId) {
      return
    }
    // automatically refetches questionnaires, it's likely they'll be stale the moment we subscribe to new teams :)
    refetch()

    const unsubs = teamIds.map(teamId =>
      client
        .subscription<
          ResultOf<typeof teamQuestionnaireState>,
          VariablesOf<typeof teamQuestionnaireState>
        >(teamQuestionnaireState, {
          teamId,
        })
        .subscribe(() => {})
    )

    return () => {
      unsubs.forEach(({ unsubscribe }) => unsubscribe())
    }
  }, [client, exerciseId, refetch, teamIds])

  useGenericActionLogEvent()
}

export default useQuestionnaireSubscriptionInstructor
