import { PropsWithChildren, useEffect, useRef } from 'react'
import { AuthService } from '../authService.ts'
import { useUser } from '../../user/user.ts'

interface RefreshUserProps {
  authService: AuthService
}

export default function RefreshUser({
  authService,
  children,
}: PropsWithChildren<RefreshUserProps>) {
  const user = useUser()
  const didRefresh = useRef(false)

  useEffect(() => {
    const timeoutId = setTimeout(async () => {
      if (didRefresh.current) return
      if (user == null) return
      didRefresh.current = true
      await authService.refreshUser(user.userId)
    })
    return () => clearTimeout(timeoutId)
  }, [authService, user])

  return <>{children}</>
}
