import axios from "axios";
import router from "@/router/index";

const url = process.env.VUE_APP_ROOT_URL;

const ApiServiece = axios.create({
  baseURL: url,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
});

ApiServiece.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

ApiServiece.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error?.status === 401) {
        router.push({ name: "login-v2" });
    }
    return Promise.reject(error);
  }
);

export default ApiServiece;
