import { Navigate } from 'react-router-dom';
import { useCan } from './useCan';

/** Conditionally render children if the user holds (module, action). */
export default function Can({ module, action, fallback = null, children }) {
  const can = useCan();
  return can(module, action) ? <>{children}</> : fallback;
}

/** Route-level guard: redirect to /unauthorized if the user lacks (module, action). */
export function RequirePermission({ module, action, children }) {
  const can = useCan();
  if (module && action && !can(module, action)) {
    return <Navigate to="/unauthorized" replace />;
  }
  return children;
}
