import axios from "axios";
import { refreshToken } from "../services/authService";
import { getStorageToken } from "../services/tokenService";
const axiosApiInstance = axios.create();
const axio2 = axios.create();

axio2.interceptors.request.use(
  async (config) => {
    const token = getStorageToken();
    config.headers = {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
      "Content-Type": "multipart/form-data",
    };
    config.maxBodyLength = 350000;
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptor for API calls
axio2.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    const originalRequest = error.config;
    if (error.response !== undefined && originalRequest !== undefined) {
      if (error.response.status === 403 && !originalRequest._retry) {
        originalRequest._retry = true;
        const access_token = await refreshToken();
        axios.defaults.headers.common["Authorization"] =
          "Bearer " + access_token;
        return axiosApiInstance(originalRequest);
      }
    }
    return Promise.reject(error);
  }
);

axiosApiInstance.interceptors.request.use(
  async (config) => {
    const token = getStorageToken();
    config.headers = {
      Authorization: `Bearer ${token}`,
      Accept: "*/*",
      "Content-Type": "application/json",
    };
    config.maxBodyLength = 350000;
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptor for API calls
axiosApiInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    const originalRequest = error.config;
    if (error.response.status === 403 && !originalRequest._retry) {
      originalRequest._retry = true;
      const access_token = await refreshToken();
      axios.defaults.headers.common["Authorization"] = "Bearer " + access_token;
      return axiosApiInstance(originalRequest);
    }
    return Promise.reject(error);
  }
);

export { axio2, axiosApiInstance };
