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 } from '@/lib/supertokens/client'

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 {
        resetRefreshFlag();
        const refreshed = await attemptRefreshingSession()

        if (refreshed) {
          const urlParams = new URLSearchParams(window.location.search)
          const redirect = urlParams.get('redirect')

          if (redirect && !redirect.includes('_serverFn') && !redirect.includes('/api/')) {
            window.location.href = decodeURIComponent(redirect)
          } else {
            window.location.href = '/';
          }
        } else {
          window.location.href = '/login'
        }
      } catch (error) {
        window.location.href = '/login'
      }
    }

    setTimeout(handleRefresh, 100)
  }, [])

  return <FullScreenLoader />
}