import axios, { type AxiosRequestConfig } from "axios";

// použij tohle pro API vyžadující autentizaci
export const privateApi = axios.create({
  withCredentials: true, // potřebuje HttpOnly cookies
});

// Set baseURL at runtime (using Function to hide from orval's esbuild)
try {
  const getEnv = new Function('return import.meta.env.VITE_BACKEND_URL');
  privateApi.defaults.baseURL = getEnv() || "http://localhost:8000";
} catch {
  privateApi.defaults.baseURL = "http://localhost:8000";
}

privateApi.interceptors.response.use(
  (res) => res,
  async (error) => {
    const original = error.config;

    if (error.response?.status === 401 && !original._retry) {
      original._retry = true;

      try {
        await privateApi.post("/api/account/token/refresh/");
        return privateApi(original);
      } catch {
        // optional: logout
      }
    }

    return Promise.reject(error);
  }
);


export const privateMutator = async <T>(
  config: AxiosRequestConfig
): Promise<T> => {
  // If sending FormData, remove Content-Type header to let axios set it with boundary
  if (config.data instanceof FormData) {
    delete config.headers?.['Content-Type'];
  }
  
  const response = await privateApi.request<T>(config);
  return response.data;
};