import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { seoApi } from '@/db/api';

export const RedirectHandler: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const checkRedirects = async () => {
      try {
        const redirects = await seoApi.getRedirects();
        const activeRedirects = redirects.filter(r => r.is_active);
        
        const currentPath = location.pathname;
        const matchedRedirect = activeRedirects.find(r => r.from_path === currentPath);
        
        if (matchedRedirect) {
          console.log(`Redirecting from ${currentPath} to ${matchedRedirect.to_path}`);
          // redirect_type can be used if we had a server-side redirect, 
          // but for SPA we just navigate.
          navigate(matchedRedirect.to_path, { replace: true });
        }
      } catch (error) {
        console.error('Redirect check error:', error);
      }
    };

    checkRedirects();
  }, [location.pathname, navigate]);

  return null;
};
