import { useState, useEffect } from 'react';
import accountantSecurityService, { MFAStatus } from '../../features/security/services/accountantSecurityService';
import useAuthStore from '../../store/useAuthStore';

/**
 * Hook to fetch and check MFA status for accountant/admin users
 */
export const useMfaStatus = () => {
  const { userInfo } = useAuthStore();
  const [mfaStatus, setMfaStatus] = useState<MFAStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const isFinancialRole = userInfo?.role === 'accountant' || userInfo?.role === 'admin';

  useEffect(() => {
    if (!isFinancialRole) {
      setLoading(false);
      return;
    }

    const fetchMfaStatus = async () => {
      try {
        setLoading(true);
        setError(null);
        const response = await accountantSecurityService.getMFAStatus();
        setMfaStatus(response.data);
      } catch (err: unknown) {
        const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
        setError(detail || (err instanceof Error ? err.message : 'Failed to load MFA status'));
        setMfaStatus(null);
      } finally {
        setLoading(false);
      }
    };

    fetchMfaStatus();
  }, [isFinancialRole, userInfo?.role]);

  const requiresMfaButNotEnabled = mfaStatus 
    ? (mfaStatus.requires_mfa || mfaStatus.is_enforced) && !mfaStatus.mfa_enabled
    : false;

  return {
    mfaStatus,
    loading,
    error,
    requiresMfaButNotEnabled,
    isFinancialRole,
  };
};

