import axios from "axios";
import { Pages } from "./Pages";

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});

axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 401) {
      localStorage.removeItem(import.meta.env.VITE_TOKEN_NAME);
      window.location.href = Pages.auth.login;
    }
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.request.use(async function (config) {
  const token = localStorage.getItem(import.meta.env.VITE_TOKEN_NAME)
    ? localStorage.getItem(import.meta.env.VITE_TOKEN_NAME)
    : "";

  config.headers.Authorization = "Bearer " + token;
  return config;
});

export default axiosInstance;
