import { apiClient } from "./httpClients";

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

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