<script setup>
import axios from 'axios';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useSession } from 'src/composables/useSession';

const quasar = useQuasar();
const router = useRouter();
const session = useSession();
const { t } = useI18n();
const { isLoggedIn } = session;

quasar.iconMapFn = (iconName) => {
    if (iconName.startsWith('vn:')) {
        const name = iconName.substring(3);

        return {
            cls: `icon-${name}`,
        };
    }
};

function responseError(error) {
    let message = error.message;
    let logOut = false;

    switch (error.response?.status) {
        case 401:
            message = 'login.loginError';

            if (isLoggedIn()) {
                message = 'errors.statusUnauthorized';
                logOut = true;
            }
            break;
        case 403:
            message = 'errors.statusUnauthorized';
            break;
        case 500:
            message = 'errors.statusInternalServerError';
            break;
        case 502:
            message = 'errors.statusBadGateway';
            break;
        case 504:
            message = 'errors.statusGatewayTimeout';
            break;
    }

    let translatedMessage = t(message);
    if (!translatedMessage) translatedMessage = message;

    quasar.notify({
        message: translatedMessage,
        type: 'negative',
    });

    if (logOut) {
        session.destroy();
        router.push({ path: '/login' });
    }

    return Promise.resolve(error);
}

axios.interceptors.response.use((response) => response, responseError);
</script>

<template>
    <router-view />
</template>

<style lang="scss">
.body--light {
    background-color: #eee;
}
</style>
