import { Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { ReactNode } from 'react';

interface PrivateRouteProps {
    children: ReactNode;
    /** Si fourni, accès restreint aux rôles listés */
    roles?: string[];
}

const PrivateRoute = ({ children, roles }: PrivateRouteProps): JSX.Element => {
    const { user, hasRole } = useAuth();

    if (!user) {
        return <Navigate to="/login" replace />;
    }

    if (roles && roles.length > 0 && !hasRole(...roles)) {
        return <Navigate to="/dashboard" replace />;
    }

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

export default PrivateRoute;