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';
import { i18n } from 'src/boot/i18n';

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;
        config.headers['Accept-Language'] = i18n.global.locale.value;
    }
    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);

    if (session.isLoggedIn() && error.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);
    }

    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 };
