import axios from "axios";
import { setIsLoggedIn } from "@/src/redux/authSlice";
import { store } from "@/src/redux/store";

const apiUrl = process.env["NEXT_PUBLIC_DEV_URL"];

console.log(apiUrl, "is url");

const axiosInstance = axios.create({
  baseURL: apiUrl,
});

// REQUEST INTERCEPTOR
axiosInstance.interceptors.request.use((config) => {
  const isUserRoute =
    window.location.pathname.includes("user") ||
    window.location.pathname.startsWith("/verify-address-payment") ||
    window.location.pathname.startsWith("/verify-payment");
  const token = localStorage.getItem(isUserRoute ? "userToken" : "adminToken");

  if (!token) {
    store.dispatch(setIsLoggedIn(false));
    throw new axios.Cancel("Token not found");
  }

  if (config.headers) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});

// RESPONSE INTERCEPTOR
axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    console.log(error, "is errror on instance");
    if (
      error.response &&
      (error.response.status === 401 ||
        error.response.data?.message?.toLowerCase().includes("token"))
    ) {
      store.dispatch(setIsLoggedIn(false));
      localStorage.clear();
      console.log("this ran on instance");
    }

    return Promise.reject(error);
  }
);

export default axiosInstance;
