import {getCookie, setCookie} from "react-use-cookie";
import jwtDecode from "jwt-decode";

export async function refreshToken({user, setUser}) {
    const init = {
        method: "POST",
        referrer: "same-origin",
    };
    return fetch("/api/refresh", init)
        .then((response) => {
            if (!response.ok) {
                throw new Error("server rejected refresh");
            }
            const user = maybeGetUser();
            if (user == null) {
                throw new Error("bad token response");
            }
            setUser(user);
        })
        .catch((error) => {
            console.log(error);
            setUser(null);
        })
} 

export function maybeGetUser() {
    const token = getCookie("token");
    if (token == null || token == "") {
        return null;
    }

    const jwt = jwtDecode(token);
    if (jwt.iss !== "react-go-forum") {
        return null;
    }

    const expiry_date = (() => {
        var time = new Date(Date.UTC, 0, 1);
        time.setUTCSeconds(jwt.exp);
        return time;
    })();
    if (expiry_date <= new Date(Date.now())) {
        return null;
    }

    return {
        id: jwt.sub,
        expiry: expiry_date,
    }
}

export function maybeAuthFromCookie(userState) {
    const user = maybeGetUser();
    if (user == null) {
        return false;
    }

    const [_, setUser] = userState;
    setUser(user);
    return true;
}

export function logout(setUser) {
    setCookie("token", "", {path: "/"});
    setUser(null);
}