import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useEstablishment } from '@/context/EstablishmentContext';
import { FE_USERS_LOGIN_URL, getRedirectUrlFromRole } from '@/utils/Url';
import logger from '@/utils/logger';

const ProtectedRoute = ({ children, requiredRight }) => {
  const { user, profileRole } = useEstablishment();
  const router = useRouter();
  const [hasRequiredRight, setHasRequiredRight] = useState(false);

  // Vérifier si l'utilisateur a au moins un rôle correspondant au requiredRight
  useEffect(() => {
    logger.debug({
      user,
      profileRole,
      requiredRight,
      hasRequiredRight,
    });

    if (user && profileRole !== null) {
      let requiredRightChecked = false;
      if (requiredRight && Array.isArray(requiredRight)) {
        // Vérifier si l'utilisateur a le droit requis
        requiredRightChecked = requiredRight.some(
          (right) => profileRole === right
        );
      } else {
        requiredRightChecked = profileRole === requiredRight;
      }
      setHasRequiredRight(requiredRightChecked);

      // Vérifier si l'utilisateur a le droit requis mais pas le bon role on le redirige la page d'accueil associé au role
      if (!requiredRightChecked) {
        const redirectUrl = getRedirectUrlFromRole(profileRole);
        if (redirectUrl !== null) {
          router.push(`${redirectUrl}`);
        }
      }
    } else {
      // User non authentifié
      router.push(`${FE_USERS_LOGIN_URL}`);
    }
  }, [user, profileRole]);

  // Autoriser l'affichage si authentifié et rôle correct
  return hasRequiredRight ? children : null;
};

export default ProtectedRoute;
