import axios from "axios";
import { env } from "$env/dynamic/public";
import UserSvelte, { type UserObj } from "./User.svelte";
import { goto } from "$app/navigation";

export async function isAuthenticated() {
    if (location.pathname.startsWith("/login")) {
        return true;
    }
    return axios
        .get(`${env.PUBLIC_JEOPARDY_SERVER_PROTOCOL}://${env.PUBLIC_JEOPARDY_SERVER}/auth`, {
            withCredentials: true
        })
        .then((res) => {
            if (res.status === 200) {
                UserSvelte.user = res.data as UserObj;
                console.log(UserSvelte.id, UserSvelte.username, UserSvelte.role);
                return true;
            } else {
                goto("/login");
            }
        })
        .catch(() => {
            goto("/login");
        });
}
