import { useNavigate } from "react-router-dom";
import { apiClient } from "./httpClients";

export function guard(evaluator, redirect, navigateOptions, onRedirect) {
    if (!evaluator) throw new Error("evaluator required.");
    if (!redirect) throw new Error("redirect required.");
    if (!navigateOptions) {
        navigateOptions = {
            replace: true
        };
    }
    let navigate = useNavigate();
    let redirecting = !evaluator();
    if (redirecting) {
        if (onRedirect) onRedirect();
        navigate(redirect, navigateOptions);
    }
}

export async function needUser() {
    let userDataResponse = await apiClient.get("/user");
    guard(() => userDataResponse.status === 200, "/login");
    return userDataResponse.data;
}