import { useEffect } from 'react'
import { getConfigValue } from '@brojs/cli'
import { api } from '../__data__/api/api'
import { isTeacher } from '../utils/user'
import { User } from '../__data__/model'

// Using any for user type to avoid type errors with the store user object
export const useAccessCode = (lessonId: string, user: any) => {
  const {
    isFetching,
    data: accessCode,
    isSuccess,
    refetch,
  } = api.useCreateAccessCodeQuery(
    { lessonId },
    {
      skip: !isTeacher(user),
      pollingInterval:
        Number(getConfigValue('journal.polling-interval')) || 3000,
      skipPollingIfUnfocused: true,
    },
  )

  const [manualAdd, manualAddRqst] = api.useManualAddStudentMutation()

  useEffect(() => {
    if (manualAddRqst.isSuccess) {
      refetch()
    }
  }, [manualAddRqst.isSuccess, refetch])

  const handleManualAdd = (user: User) => manualAdd({ lessonId, user })

  return {
    isFetching,
    accessCode,
    isSuccess,
    refetch,
    manualAddRqst,
    handleManualAdd
  }
} 