import axios from 'axios';
import { Notify } from 'quasar';
import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router';
import { i18n } from './i18n';

const session = useSession();
const { t } = i18n.global;

axios.defaults.baseURL = '/api/';

const onRequest = (config) => {
    const token = session.getToken();
    if (token.length && !config.headers.Authorization) {
        config.headers.Authorization = token;
    }

    return config;
};

const onRequestError = (error) => {
    return Promise.reject(error);
};

const onResponse = (response) => {
    const { method } = response.config;

    const isSaveRequest = method === 'patch';
    if (isSaveRequest) {
        Notify.create({
            message: t('globals.dataSaved'),
            type: 'positive',
        });
    }

    return response;
};

const onResponseError = (error) => {
    let message = '';

    const response = error.response;
    const responseData = response && response.data;
    const responseError = responseData && response.data.error;
    if (responseError) {
        message = responseError.message;
    }

    switch (response?.status) {
        case 500:
            message = 'errors.statusInternalServerError';
            break;
        case 502:
            message = 'errors.statusBadGateway';
            break;
        case 504:
            message = 'errors.statusGatewayTimeout';
            break;
    }

    if (session.isLoggedIn() && response?.status === 401) {
        session.destroy();
        const hash = window.location.hash;
        const url = hash.slice(1);
        Router.push({ path: url });
    } else if (!session.isLoggedIn()) {
        return Promise.reject(error);
    }

    Notify.create({
        message: t(message),
        type: 'negative',
    });

    return Promise.reject(error);
};

axios.interceptors.request.use(onRequest, onRequestError);
axios.interceptors.response.use(onResponse, onResponseError);

export { onRequest, onResponseError };
