import { useAuth } from '@context-providers/auth-context-provider'
import { AuthorizedPageLayout } from '@pages/authorized-page-layout'
import { createFileRoute } from '@tanstack/react-router'

import { useEffect } from 'react'

/**
 * Auth Route Guard
 * all routes that require authentication are rendered with auth context
 * if the user is not authenticated, when accessing an auth-route, the redirect to the login page is executed
 */
export const Route = createFileRoute('/_auth-routes')({
  component: AuthGuard,
})

function AuthGuard() {
  const navigate = Route.useNavigate()
  const { loginState } = useAuth()

  useEffect(() => {
    if (loginState === 'loggedOut') {
      // store the redirect url as search param, if not authorized, to restore after keycloak login
      void navigate({ to: '/login', search: { redirectUrl: location.pathname + location.search } })
    }
  }, [loginState, navigate])

  // Don't render anything until authenticated (redirect effect handles navigation)
  if (loginState !== 'loggedIn') {
    return null
  }

  return <AuthorizedPageLayout />
}
