import { useState } from './useState';
import { useRole } from './useRole';
import { useUserConfig } from './useUserConfig';
import axios from 'axios';
import useNotify from './useNotify';

export function useSession() {
    const { notify } = useNotify();

    function getToken() {
        const localToken = localStorage.getItem('token');
        const sessionToken = sessionStorage.getItem('token');

        return localToken || sessionToken || '';
    }
    function getTokenMultimedia() {
        const localTokenMultimedia = localStorage.getItem('tokenMultimedia');
        const sessionTokenMultimedia = sessionStorage.getItem('tokenMultimedia');

        return localTokenMultimedia || sessionTokenMultimedia || '';
    }

    function setToken(data) {
        if (data.keepLogin) {
            localStorage.setItem('token', data.token);
            localStorage.setItem('tokenMultimedia', data.tokenMultimedia);
        } else {
            sessionStorage.setItem('token', data.token);
            sessionStorage.setItem('tokenMultimedia', data.tokenMultimedia);
        }
    }
    async function destroyToken(url, storage, key) {
        if (storage.getItem(key)) {
            try {
                await axios.post(url, null, {
                    headers: { Authorization: storage.getItem(key) },
                });
            } catch (error) {
                notify('errors.statusUnauthorized', 'negative');
            } finally {
                storage.removeItem(key);
            }
        }
    }
    async function destroy() {
        const tokens = {
            tokenMultimedia: 'Accounts/logout',
            token: 'VnUsers/logout',
        };
        for (const [key, url] of Object.entries(tokens)) {
            await destroyToken(url, localStorage, key);
            await destroyToken(url, sessionStorage, key);
        }

        const { setUser } = useState();

        setUser({
            id: 0,
            name: '',
            nickname: '',
            lang: '',
            darkMode: null,
        });
    }

    async function login(token, tokenMultimedia, keepLogin) {
        setToken({ token, tokenMultimedia, keepLogin });

        await useRole().fetch();
        await useUserConfig().fetch();
    }

    function isLoggedIn() {
        const localToken = localStorage.getItem('token');
        const sessionToken = sessionStorage.getItem('token');

        return !!(localToken || sessionToken);
    }

    return {
        getToken,
        getTokenMultimedia,
        setToken,
        destroy,
        login,
        isLoggedIn,
    };
}
