import { useEffect, useState } from 'react';
import api from '../../services/api'; // Import the Axios instance with the interceptor
import { useNavigate } from 'react-router-dom';
import { generateUniqueId } from '../../shared/utils/crypto';

const UserSessionListener = () => {
  const navigate = useNavigate();
  const [isRedirecting, setIsRedirecting] = useState(false);

  const userId = generateUniqueId(); // Use the unique ID generator for anonymous users

  useEffect(() => {
    const fetchUserSession = async () => {
      try {
        // Get the user's current session ID from the API
        const response = await api.get(`/users/${userId}/session`);

        const currentSessionId =
          response.data.currentSessionId || generateUniqueId();

        // Only redirect if the user is not already being redirected
        if (
          !isRedirecting &&
          currentSessionId &&
          currentSessionId.startsWith('lobby')
        ) {
          setIsRedirecting(true);

          // Delete the user from the session via API
          await api.delete(`/users/${userId}`);

          // Redirect to the session
          navigate(`/${currentSessionId}`);

          setIsRedirecting(false);
        }
      } catch (error) {
        console.error('Error fetching user session:', error);
      }
    };

    fetchUserSession();
  }, [userId, navigate, isRedirecting]);

  return null;
};

export default UserSessionListener;
