import axios from "axios";

const axiosInstance = axios.create({
  baseURL: process.env.API_URL,
});

// Clear existing interceptors to prevent multiple registrations
const clearInterceptors = () => {
  const requestInterceptor = axiosInstance.interceptors.request.use();
  const responseInterceptor = axiosInstance.interceptors.response.use();

  if (requestInterceptor) {
    axiosInstance.interceptors.request.eject(requestInterceptor);
  }

  if (responseInterceptor) {
    axiosInstance.interceptors.response.eject(responseInterceptor);
  }
};

export const SetupAxiosInterceptors = (inputToken: string | null) => {
  console.log("[debug] set up interceptors", inputToken);

  // Clear existing interceptors
  clearInterceptors();

  // Request interceptor
  axiosInstance.interceptors.request.use(
    (config) => {
      // Use the token passed in or retrieve from localStorage
      const token = inputToken ?? localStorage.getItem("accessToken");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  console.log("[debug] set up interceptors2", inputToken);

  // Response interceptor
  axiosInstance.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      console.error("API Error:", error.response?.data || error);
      return Promise.reject(error);
    },
  );
};

export default axiosInstance;
