import { createFileRoute, redirect } from '@tanstack/react-router'

/**
 * 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')({
  beforeLoad: ({ context }) => {
    const { isAuthenticated } = context.auth

    if (!isAuthenticated) {
      // store the redirect url as search param, if not authorized, to restore after keycloak login
      throw redirect({ to: '/login', search: { redirectUrl: location.pathname + location.search } })
    }

    // if the user is authorized - do nothing (no redirect; required page is loaded)
  },
})
