import { useEffect } from 'react'
import type { GetTeamQuestionnaireState } from '../queries/GetTeamQuestionnaireState.generated'
import { useGetTeamQuestionnaireState } from '../queries/GetTeamQuestionnaireState.generated'
import type { TeamQuestionnaireState } from '../subscriptions/TeamQuestionnaireState.generated'
import { TeamQuestionnaireStateDocument } from '../subscriptions/TeamQuestionnaireState.generated'

const useTeamQuestionnaireStateSubscription = (
  teamId: string,
  questionnaireId: string
) => {
  const query = useGetTeamQuestionnaireState({
    variables: {
      teamId,
      questionnaireId,
    },
    fetchPolicy: 'cache-and-network',
  })

  const { subscribeToMore } = query

  useEffect(
    () =>
      subscribeToMore({
        document: TeamQuestionnaireStateDocument,
        variables: {
          teamId,
          questionnaireId,
        },
        updateQuery: (prev, { subscriptionData }) => {
          const retypedData =
            subscriptionData as unknown as TeamQuestionnaireState

          if (!retypedData) return prev
          const newState =
            retypedData.teamQuestionnaireState?.teamQuestionnaireState
          if (newState) {
            return {
              ...prev,
              questionnaireState: newState,
            } as GetTeamQuestionnaireState
          }
          return prev
        },
      }),
    [questionnaireId, subscribeToMore, teamId]
  )

  return query
}

export default useTeamQuestionnaireStateSubscription
