import axios from "axios";

const vite_url = import.meta.env.VITE_URL;

export function check_validity(online_callback = () => {
}) {
    return axios.get(`${vite_url}/api/auth`).then(data => {
        if (data.data) {
            axios.get(`${vite_url}/api/auth/userinfo`).then(data => {
                online_callback({state: true, userinfo: data.data});
            })
        }else{
            online_callback({state: false});
        }
    }).catch(() => {
        console.log("=> Not authenticated");
        online_callback({state: false});
    })
}

export function login() {
    sessionStorage.setItem("next", window.location.href)
    window.location.href = `${vite_url}/api/auth/login`;
}

export function login_redirect() {
    const next = sessionStorage.getItem("next")
    if (next) {
        sessionStorage.removeItem("next")
        window.location.href = next
    } else {
        window.location.href = import.meta.env.VITE_URL
    }
}

export function logout() {
    window.location.href = `${vite_url}/api/logout`;
}
