import axios from "axios";
import { auth } from "../firebase/firebase.utils";
import InstanceRenderManager from "./instanceRenderMgr";

axios.defaults.baseURL =
  import.meta.env.VITE_APP_AXIOS_BASE_API_URL ||
  (import.meta.env.MODE === "production" ? "https://api.imex.online/" : "http://localhost:4000/");

export const axiosAuthInterceptorId = axios.interceptors.request.use(
  async (config) => {
    if (!config.headers.Authorization) {
      const token = auth.currentUser && (await auth.currentUser.getIdToken());
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      InstanceRenderManager({
        executeFunction: true,
        args: [],
        promanager: () => {
          if (!config.url.startsWith("http://localhost:1337")) {
            config.headers["Convenient-Company"] = "promanager";
          }
        }
      });
    }

    return config;
  },
  (error) => Promise.reject(error)
);

const cleanAxios = axios.create();
cleanAxios.interceptors.request.eject(axiosAuthInterceptorId);

export default cleanAxios;
