import { Navigate } from 'react-router-dom';
import { useAuthStore } from '../../store/authStore';

/**
 * AdminGuard
 * Route-level RBAC gate for the Control Room.
 * Redirects non-admin users to /command silently.
 * Defense-in-depth: API also enforces ADMIN role via middleware.
 */
export function AdminGuard({ children }: { children: React.ReactNode }) {
  const { user, isAuthenticated } = useAuthStore();

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

  const role = String(user?.role ?? '').trim().toUpperCase();
  const isAdmin = role === 'ADMIN' || role === 'SALES_DIRECTOR' || role === 'SUPERADMIN';

  if (!isAdmin) {
    // Silent redirect — no error screen (security through obscurity)
    return <Navigate to="/command" replace />;
  }

  return <>{children}</>;
}
