import { usePermission } from "./context/permission-context";

export function AccessGuard({
  module,
  action,
  children,
  fallback = null,
}: {
  module?: string;
  action?: string;
  children: React.ReactNode;
  fallback?: React.ReactNode;
}) {
  const { canModule, canAction, can, loading } = usePermission();

  if (loading) return null;

  // ❗ WAJIB ADA RULE
  if (!module && !action) {
    if (process.env.NODE_ENV === "development") {
      console.warn("AccessGuard requires module and/or action");
    }
    return fallback;
  }

  if (module && action && !can(module, action)) return fallback;
  if (module && !action && !canModule(module)) return fallback;
  if (!module && action && !canAction(action)) return fallback;

  return <>{children}</>;
}
