import { Navigate } from "react-router-dom";
import type { PropsWithChildren } from "react";
import { useAuth } from "@modules/auth";
import { useAuthStore } from "@modules/auth/store/authStore";

export function AdminGuard({ children }: PropsWithChildren): JSX.Element | null {
  const bootstrapped = useAuthStore((state) => state.bootstrapped);
  const auth = useAuth();

  if (!bootstrapped) {
    return null;
  }

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

  if (auth.user?.role !== "admin") {
    return <Navigate to="/" replace />;
  }

  return <>{children}</>;
}
