import axios from "axios";
import { useUserStore } from "../context/zustand-store/userStore";
import { toast } from "react-toastify";
import { checkIsMobile } from "./checkIsMobile";

let hasShownUnauthorizedToast = false;

const api = axios.create({
  baseURL: "https://inspectionbackend.rasadyar.com/",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  withCredentials: true,
});

api.interceptors.request.use(
  (config) => {
    const token = useUserStore.getState().auth;
    if (token) {
      config.headers.Authorization = `${token}`;
    }

    // If URL is a full URL (starts with http:// or https://), it's an external API
    // Clear baseURL and disable credentials to avoid CORS issues
    if (
      config.url?.startsWith("http://") ||
      config.url?.startsWith("https://")
    ) {
      config.baseURL = "";
      config.withCredentials = false;
    }

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

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401 && useUserStore.getState().auth) {
      const logOut = useUserStore.getState().logOut;

      if (!hasShownUnauthorizedToast) {
        hasShownUnauthorizedToast = true;
        toast.error("مجددا وارد شوید!", {
          position: checkIsMobile() ? "bottom-center" : "top-center",
          theme: "light",
          rtl: true,
        });
        if (typeof logOut === "function") {
          window.location.href = "/";
          logOut();
        }
      }
    }
    return Promise.reject(error);
  },
);

export default api;
