import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../../hooks/use-auth';

export const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated } = useAuthStore();
  const location = useLocation();

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  return <>{children}</>;
};

export const RequireRole: React.FC<{ children: React.ReactNode; role: 'ADMIN' | 'PARTNER_USER' }> = ({ children, role }) => {
  const { user } = useAuthStore();

  if (user?.role !== role) {
    // If they are an admin trying to access client route, they should be redirected
    if (user?.role === 'ADMIN') return <Navigate to="/admin" replace />;
    if (user?.role === 'PARTNER_USER') return <Navigate to="/client" replace />;
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};

export const RequireOnboardingComplete: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { user } = useAuthStore();
  
  // If the user hasn't completed onboarding, redirect to the onboarding wizard
  if (user && user.onboardingStatus !== 'APPROVED') {
    return <Navigate to="/onboarding" replace />;
  }

  return <>{children}</>;
};
