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

let hasShownUnauthorizedToast = false;
const getBaseURL = () => {
  const hostname =
    typeof window !== "undefined" ? window.location.hostname : "";
  return hostname === "dam.rasadyar.com"
    ? "https://api.dam.rasadyar.com"
    : "https://api.tdam.rasadyar.com";
};

const api = axios.create({
  baseURL: getBaseURL(),
  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 = `Bearer ${token}`;
    }
    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") {
          logOut();
        }
      }
    }
    return Promise.reject(error);
  }
);

export default api;
