import axios from "axios";
import store from "@/store";

const ASSET_URL = import.meta.env.VITE_ASSET_URL || "";

const api = axios.create({
    baseURL: ASSET_URL,
    headers: {
        accept: "application/json",
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
        Authorization: `Bearer ${store.state.auth.user.api_token}`,
    },
    contentType: false,
    processData: false,
});

api.interceptors.request.use(
    (config) => {
        store.commit("SET_LOADING", true);
        return config;
    },
    (error) => Promise.reject(error)
);

api.interceptors.response.use(
    (res) => {
        store.commit("SET_LOADING", false);
        return res;
    },
    (error) => {
        store.commit("SET_LOADING", false);
        if (error.response.status === 419 || error.response.status === 401) {
            localStorage.removeItem("APP_USER_TOKEN");
            store.commit("auth/SET_USER", {});
            store.commit("auth/SET_AUTHENTICATED", false);
            window.location = "/";
        }
        return Promise.reject(error)
    }
);

export { api };