import { useAuth } from './useAuth';
import { useUserRole } from './useUserRole';
import { useEffect, useState } from 'react';
import { getEnrolledFactors } from '@/lib/authService';

export function useRequireMFA() {
  const { aal, session } = useAuth();
  const { isModerator, isAdmin, loading: roleLoading } = useUserRole();
  const [isEnrolled, setIsEnrolled] = useState(false);
  const [loading, setLoading] = useState(true);
  
  // Check actual enrollment status
  useEffect(() => {
    const checkEnrollment = async () => {
      if (!session) {
        setIsEnrolled(false);
        setLoading(false);
        return;
      }
      
      const factors = await getEnrolledFactors();
      setIsEnrolled(factors.length > 0);
      setLoading(false);
    };
    
    if (!roleLoading) {
      checkEnrollment();
    }
  }, [session, roleLoading]);
  
  // MFA is required for moderators and admins
  const requiresMFA = isModerator() || isAdmin();
  
  // User has MFA if they have AAL2 AND have enrolled factors
  const hasMFA = aal === 'aal2' && isEnrolled;
  
  // User needs to verify MFA if they're enrolled but session is still at AAL1
  const needsVerification = requiresMFA && isEnrolled && aal === 'aal1';
  
  return {
    requiresMFA,
    hasMFA,
    isEnrolled,
    needsEnrollment: requiresMFA && !isEnrolled,
    needsVerification,
    aal,
    loading: loading || roleLoading,
  };
}
