File size: 2,481 Bytes
9853396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useEffect } from 'react';
import { useState } from 'react';
import { useRouter } from '@tanstack/react-router';
import { Skeleton } from '@/components/ui/skeleton';
import { useSystemStatus } from '@/features/auth/data/initialization';

interface InitializationGuardProps {
  children: React.ReactNode;
}

export function InitializationGuard({ children }: InitializationGuardProps) {
  const router = useRouter();
  const { data: systemStatus, isLoading, error } = useSystemStatus();
  const [isNavigating, setIsNavigating] = useState(false);

  useEffect(() => {
    // Only redirect if we have data and system is not initialized
    if (systemStatus && !systemStatus.isInitialized) {
      // Check if we're not already on the initialization page
      const currentPath = window.location.pathname;
      if (currentPath !== '/initialization') {
        setIsNavigating(true);
        //@ts-ignore
        router.navigate({ to: '/initialization' }).finally(() => {
          setIsNavigating(false);
        });
      }
    }
  }, [systemStatus, router]);

  // Show loading skeleton while checking system status
  if (isLoading) {
    return (
      <div className='flex h-screen items-center justify-center'>

        <div className='space-y-4'>

          <Skeleton className='h-8 w-48' />

          <Skeleton className='h-4 w-32' />

        </div>

      </div>
    );
  }

  // Show error if failed to check system status
  if (error) {
    return (
      <div className='flex h-screen items-center justify-center'>

        <div className='text-center'>

          <h1 className='text-2xl font-bold text-red-600'>System Error</h1>

          <p className='text-muted-foreground'>Failed to check system status</p>

        </div>

      </div>
    );
  }

  // If system is not initialized and we're not on initialization page, don't render children
  // But allow navigation to complete naturally
  if ((systemStatus && !systemStatus.isInitialized && window.location.pathname !== '/initialization') || isNavigating) {
    // Don't return null immediately - let the navigation complete
    // The useEffect will handle the redirect
    return (
      <div className='flex h-screen items-center justify-center'>

        <div className='space-y-4'>

          <Skeleton className='h-8 w-48' />

          <Skeleton className='h-4 w-32' />

        </div>

      </div>
    );
  }

  return <>{children}</>;
}