import {appConfig} from "../config/app";
import {TokenUtil} from "./token";
import axios from "axios";

const instanceCp = axios.create({
    baseURL: appConfig.apiCpUrl,
    headers: {
        "Content-Type": "application/json",
    },
});

instanceCp.interceptors.request.use(
    (config) => {
        if (TokenUtil.accessToken) {
            config.headers["Authorization"] = 'Bearer ' + TokenUtil.accessToken; // for Node.js Express back-end
        }
        config.headers["ngrok-skip-browser-warning"] = true
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

instanceCp.interceptors.response.use(
    (res) => {
        return res;
    },
    async (err) => {
        const originalConfig = err.config;

        if (originalConfig.url !== "/auth/login" && err.response) {
            // Access Token was expired
            if (err.response.status === 401 && !originalConfig._retry) {
                originalConfig._retry = true;

                try {
                    if (TokenUtil.refreshToken) {
                        await authenticationRepository.api.refreshToken()
                    }
                    return instanceCp(originalConfig);
                } catch (_error) {
                    return Promise.reject(_error);
                }
            }
        }

        return Promise.reject(err);
    }
);

export const http2 = {
    fetcher: async (url) => {
        const resp = await instanceCp.get(appConfig.apiCpUrl + url);

        return resp.data;
    },
    get: async (url, opts = {}) => {
        const resp = await instanceCp.post(appConfig.apiCpUrl + url);

        return resp.data;
    },
    post: async (url, data, opts) => {
        const resp = await instanceCp.post(appConfig.apiCpUrl + url, data);

        return resp.data;
    },
    put: async (url, data, opts) => {
        const resp = await instanceCp.put(appConfig.apiCpUrl + url, data);

        return resp.data;
    },
    del: async (url, opts) => {
        const resp = await instanceCp.delete(appConfig.apiCpUrl + url);

        return resp.data;
    },
};
