import { useAuth } from '@context-providers/auth-context-provider'
import { Route } from '@routes/login'

import { useEffect } from 'react'

import type { FileRouteTypes } from '../../routeTree.gen'

/**
 * Login component
 *
 * the auth check has to be implemented with an effect, because the keycloak.init is async
 * so the isAuthenticated state is not available immediately at the "beforeLoad" option at the route level
 * that's why our login component is a non-visual component, that just checks the auth state
 * and redirects to the dashboard (landing page)
 *
 * - if authProvider is not initialized, it will wait for initializing complete
 * - if the user is not authenticated, it will execute login (redirect to keycloak)
 * - if the user is authenticated, it will wait for the user to be loaded (user !== null)
 * - if the user is loaded, it will redirect to the dashboard
 */
export const LoginPage = () => {
  const { isAuthenticated, isInitComplete, login, user } = useAuth()
  const navigate = Route.useNavigate()
  const searchParams = Route.useSearch()

  useEffect(() => {
    // wait for the keycloak init to complete
    if (!isInitComplete) {
      return
    }

    // if not authenticated yet, execute login
    if (!isAuthenticated) {
      void login() // NOSONAR
    } else if (user) {
      // if authenticated, redirect considering the user role
      if (user.userRoles.includes('unauthorized')) {
        void navigate({ to: '/unauthorized' }) // NOSONAR
      } else {
        // redirect, when the user is authenticated and loaded
        const fallbackHome: FileRouteTypes['to'] = '/dashboard'
        const href = searchParams.redirectUrl ?? fallbackHome
        // for dev mode and HMR we need to wait for the redirect; otherwise the 'href' is not found by tanstack router
        setTimeout(() => void navigate({ to: href, from: '/login' }), 0) // NOSONAR (we want to ignore the promise here)
      }
    }
  }, [isAuthenticated, isInitComplete, login, navigate, searchParams.redirectUrl, user])

  return <p>Login in progress...</p>
}
