import React, {useEffect, useContext} from "react";
import AuthContext from "../../context/auth-context";
import {Navigate, Outlet, useNavigate} from "react-router-dom";
import * as authApi from "../../API/user";

const COOKIE_LIFE = 1800000;

const AuthProtection = () => {

    const authCtx = useContext(AuthContext);
    /**
     *Redirects if unauth
     *Doesnt let u see Wrapped Routes when u arent logged in
     *Checks if session has expired every 61 mins
     */
    useEffect(() => {

        const timer = setInterval(async function () {
            try {
                const response = await authApi.checkAuth();
            } catch (error: any) {
                if (error.response.status === 401) {
                    authCtx.logoutUser();
                }
            }
        }, COOKIE_LIFE + 1000);

        return () => {
            clearInterval(timer);
        };
    }, []);

    return (
        <>
            {
                authCtx.isAuthenticated === false ?
                    <Navigate to={'./login'}></Navigate>
                    :
                    <Outlet/>
            }
        </>


    );
};

export default AuthProtection;
