import axios from 'axios';
import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router';
import useNotify from 'src/composables/useNotify.js';
import { useStateQueryStore } from 'src/stores/useStateQueryStore';

const session = useSession();
const { notify } = useNotify();
const stateQuery = useStateQueryStore();
const baseUrl = '/api/';

axios.defaults.baseURL = baseUrl;
const axiosNoError = axios.create({ baseURL: baseUrl });

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

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

const onResponse = (response) => {
    const config = response.config;
    stateQuery.remove(config);

    if (config.method === 'patch') {
        notify('globals.dataSaved', 'positive');
    }

    return response;
};

const onResponseError = (error) => {
    stateQuery.remove(error.config);

    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 422:
            if (error.name == 'ValidationError')
                message +=
                    ' "' +
                    responseError.details.context +
                    '.' +
                    Object.keys(responseError.details.codes).join(',') +
                    '"';
            break;
        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(false);
        const hash = window.location.hash;
        const url = hash.slice(1);
        Router.push(`/login?redirect=${url}`);
    } else if (!session.isLoggedIn()) {
        return Promise.reject(error);
    }

    notify(message, 'negative');

    return Promise.reject(error);
};

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

export { onRequest, onResponseError, axiosNoError };
