import { useGetAnalyticsActionLogsSuspenseQuery } from '@inject/graphql/queries/GetAnalyticsActionLogs.generated'
import type { ExerciseActionLogs } from '@inject/graphql/subscriptions/AnalyticsActionLogs.generated'
import { ExerciseActionLogsDocument } from '@inject/graphql/subscriptions/AnalyticsActionLogs.generated'
import { useEffect } from 'react'

const useAnalyticsActionLogsSubscription = (exerciseId: string) => {
  const query = useGetAnalyticsActionLogsSuspenseQuery({
    variables: { exerciseId },
  })

  const { subscribeToMore } = query
  useEffect(
    () =>
      subscribeToMore({
        document: ExerciseActionLogsDocument,
        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 ExerciseActionLogs
          if (
            !retypedData ||
            !retypedData.analyticsActionLogsSubscription ||
            !retypedData.analyticsActionLogsSubscription.actionLog
          )
            return prev

          return {
            ...prev,
            analyticsActionLogs: [
              ...(prev.analyticsActionLogs || []),
              retypedData.analyticsActionLogsSubscription.actionLog,
            ],
          }
        },
      }),
    [exerciseId, subscribeToMore]
  )

  return query
}

export default useAnalyticsActionLogsSubscription
