import { Navigate, Outlet } from "react-router";
import useAuthStore from "../stores/useAuthStore";
import api from "../utils/api";
import { useQuery } from "@tanstack/react-query";
import { User } from "../types/User";

function ProtectedPage() {
  const { token } = useAuthStore();

  const { data: user, isLoading } = useQuery({
    queryKey: ["me"],
    queryFn: () => api.get("auth/me").json<User>(),
    enabled: !!token,
  });

  if (isLoading) {
    return null;
  }

  return user ? <Outlet /> : <Navigate to="/login" />;
}

export default ProtectedPage;
