import axios from "axios";
import {
  getToken,
  getRefreshToken,
  setToken,
  setRefreshToken,
  removeToken,
  removeRefreshToken,
} from "./func";
import { refreshToken } from "../pages/auth/service/AuthService";
// import { Pages } from "./Pages";

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

axiosInstance.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    if (error?.response?.status === 401 && !originalRequest._retry) {
      if (window.isRefreshingToken) {
        // Wait for the refresh to complete
        await new Promise((resolve) => {
          const checkComplete = setInterval(() => {
            if (!window.isRefreshingToken) {
              clearInterval(checkComplete);
              resolve(true);
            }
          }, 100);
        });
        return axiosInstance(originalRequest);
      }

      originalRequest._retry = true;
      window.isRefreshingToken = true;

      try {
        const refreshTokenValue = await getRefreshToken();
        const { data } = await refreshToken({
          refreshToken: refreshTokenValue || "",
        });

        if (data?.accessToken?.token) {
          await setToken(data?.accessToken?.token);
          if (data.refreshToken?.token) {
            await setRefreshToken(data.refreshToken?.token);
          }

          originalRequest.headers.Authorization = `Bearer ${data.accessToken.token}`;
          return axiosInstance(originalRequest);
        }
      } catch (refreshError) {
        console.error("Token refresh failed:", refreshError);
        await removeToken();
        await removeRefreshToken();
        window.location.href = "/auth/login";
        return Promise.reject(refreshError);
      } finally {
        window.isRefreshingToken = false;
      }
    }
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.request.use(async function (config) {
  const tokenValue = await getToken();
  const token = tokenValue ? tokenValue : "";
  const slug = localStorage.getItem(import.meta.env.VITE_SLUG_ID);
  const slug_parse = slug ? JSON.parse(slug) : null;
  config.headers.Authorization = "Bearer " + token;
  config.headers["x-business-id"] = slug_parse?.danakSubscriptionId;
  return config;
});

export default axiosInstance;
