import { createFileRoute } from '@tanstack/react-router'
import { useEffect, useRef } from 'react'
import FullScreenLoader from '@/components/full-screen-loader'
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session'
import { resetRefreshFlag, getOrCreateRefreshPromise } from '@/lib/supertokens/client'
import { logger } from '@/lib/supertokens'

export const Route = createFileRoute('/refresh-session')({
  component: RouteComponent,
})

function RouteComponent() {
  const hasAttemptedRef = useRef(false);

  useEffect(() => {
    if (hasAttemptedRef.current) return;
    hasAttemptedRef.current = true;

    const handleRefresh = async () => {
      try {
        logger.info("Refresh session route: starting refresh");

        const refreshed = await getOrCreateRefreshPromise(async () => {
          return await attemptRefreshingSession();
        });

        if (refreshed) {
          logger.info("Refresh session route: refresh successful");
          const urlParams = new URLSearchParams(window.location.search);
          const redirect = urlParams.get('redirect');

          const safe =
            redirect &&
            redirect.startsWith('/') &&
            !redirect.startsWith('/refresh-session') &&
            !redirect.includes('_serverFn') &&
            !redirect.includes('/api/');

          if (safe) {
            logger.info("Refresh session route: redirecting to", redirect);
            window.location.href = redirect;
          } else {
            logger.info("Refresh session route: redirecting to home");
            window.location.href = '/';
          }
        } else {
          logger.warn("Refresh session route: refresh failed, redirecting to login");
          window.location.href = '/login';
        }
      } catch (error) {
        logger.error("Refresh session route: error during refresh", error);
        window.location.href = '/login';
      }
    }

    setTimeout(handleRefresh, 100)
  }, [])

  return <FullScreenLoader />
}