import {useContext} from 'react';

// auth provider
import AuthContext from '@/contexts/auth';

// ==============================|| AUTH HOOKS ||============================== //

const useAuth = () => {
    const context = useContext(AuthContext);

    if (!context) throw new Error('context must be use inside provider');

    return context;
};


const clearAuth = () => {
    localStorage.removeItem(AppConfig.AUTH_TOKEN_KEY);
    localStorage.removeItem(AppConfig.AUTHED_PERSON_DATA_KEY);
}
export const setAuthToken = (token: string | null,profileData:UserProfile|null, expiry_time = -1) => {
    if (!token) {
        clearAuth();
        return;
    }
    localStorage.setItem(AppConfig.AUTH_TOKEN_KEY, JSON.stringify({
        token, expiry_time
    }));
    localStorage.setItem(AppConfig.AUTHED_PERSON_DATA_KEY, JSON.stringify(profileData));
}

export const getAuthToken = () => {
    const data = localStorage.getItem(AppConfig.AUTH_TOKEN_KEY);
    if (!data) return;
    try {
        const {token, expiry_time} = JSON.parse(data) as { token: string, expiry_time: number };
        if (expiry_time != -1 && expiry_time < Date.now()) {
            clearAuth();
            return;
        }
        return token;
    } catch (_e) {
        return;
    }
}


export default useAuth;
