"use client"

import { useEffect, useState } from 'react';

import { useCfgRouter } from './useCfgRouter';

import { useAuth } from '../context';

interface UseAuthGuardOptions {
  redirectTo?: string;
  requireAuth?: boolean;
  /** Whether to save current URL for redirect after auth (default: true) */
  saveRedirectUrl?: boolean;
}

export const useAuthGuard = (options: UseAuthGuardOptions = {}) => {
  const { redirectTo = '/auth', requireAuth = true, saveRedirectUrl: shouldSaveUrl = true } = options;
  const { isAuthenticated, isLoading, saveRedirectUrl } = useAuth();
  const router = useCfgRouter();
  const [isRedirecting, setIsRedirecting] = useState(false);

  useEffect(() => {
    if (!isLoading && requireAuth && !isAuthenticated && !isRedirecting) {
      // Save current URL before redirecting
      if (shouldSaveUrl && typeof window !== 'undefined') {
        const currentUrl = window.location.pathname + window.location.search;
        saveRedirectUrl(currentUrl);
      }

      setIsRedirecting(true);
      router.push(redirectTo);
    }
  }, [isAuthenticated, isLoading, router, redirectTo, requireAuth, isRedirecting, shouldSaveUrl, saveRedirectUrl]);

  return { isAuthenticated, isLoading, isRedirecting };
}; 