import { onError } from '@apollo/client/link/error'

const debounced = (fn: (msg: string) => void, delay: number) => {
  let timeout: NodeJS.Timeout
  return (msg: string) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      fn(msg)
    }, delay)
  }
}

const authLink = (onFailedAuth: (msg: string) => void) =>
  onError(({ graphQLErrors }) => {
    if (graphQLErrors) {
      graphQLErrors.forEach(error => {
        if (error.message === 'Authentication failed') {
          debounced(onFailedAuth, 1000)('Authentication failed')
        }
      })
    }
  })

export default authLink
