import React from "react";

const AUTH_URL = `http://${process.env.REACT_APP_API_URL}/auth`;

interface IAuthContext {
    sessionToken: string
}

const AuthContext = React.createContext<IAuthContext>({
    sessionToken: ''
});

export const useAuth = () => React.useContext(AuthContext);

const AuthContextProvider = ({children}: any) => {
    const [sessionToken] = React.useState('');

    React.useEffect(() => {
        const token =  window.localStorage.getItem('session_token');
        if (!token) {
            fetch(AUTH_URL, {
                method: 'GET'
            }).then(res => res.json()).then(token => {
                window.localStorage.setItem('session_token', token);
            });
        }
    }, []);

    return (
        <AuthContext.Provider value={{sessionToken}}>
            {children}
        </AuthContext.Provider>
    );
};

export default AuthContextProvider;