import { useAuth0 } from "@auth0/auth0-react";
import { PropsWithChildren, useEffect } from "react";

interface Props extends PropsWithChildren<any>{
    setToken: React.Dispatch<React.SetStateAction<string | undefined>>
}

export default function AuthWrapper(props: Props) {
    const { children, setToken } = props;
    const { isLoading, loginWithRedirect, isAuthenticated, getAccessTokenSilently } = useAuth0();
    
    useEffect(() => {
        if (!isAuthenticated && !isLoading) {
            loginWithRedirect();
        }
    }, [isAuthenticated, loginWithRedirect, isLoading]);

    useEffect(() => {
        if (isAuthenticated) getAccessTokenSilently().then(t => {
            if (t.length < 1) {
                loginWithRedirect()
            }
            setToken(t)
        }).catch(() => {
            // No token, go back to login
            loginWithRedirect()
        })
    }, [setToken, isAuthenticated])

    return children;
}