import axios from "axios";
import useAuthStore from "@/stores/useAuthStore";
import useAuthPopup from "@/stores/useAuthPopup";

const useApiClient = () => {
  const { getToken } = useAuthStore();
  const authPopup = useAuthPopup();

  const apiClient = axios.create({
    baseURL: "http://192.168.1.5:4000/",
    headers: {
      "Content-Type": "application/json",
    },
  });

  apiClient.interceptors.request.use(
    (config) => {
      const token = getToken();

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

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

  apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
      if (error.response?.status === 401) {
        console.error("Authentication error:", error);
        authPopup.open();
      }
      return Promise.reject(error);
    }
  );

  return apiClient;
};

export default useApiClient;
