import axios from "axios";

// Usa variabile ambiente o fallback a window.location per accesso esterno
const getApiBaseUrl = (): string => {
  // Prima controlla la variabile ambiente (deve essere non-vuota)
  const envUrl = import.meta.env.VITE_API_URL;
  if (envUrl && envUrl.trim() !== "") {
    return `${envUrl}/api`;
  }
  // Fallback: usa lo stesso host del frontend ma porta 5000
  const protocol = window.location.protocol;
  const hostname = window.location.hostname;
  return `${protocol}//${hostname}:5000/api`;
};

const api = axios.create({
  baseURL: getApiBaseUrl(),
  headers: {
    "Content-Type": "application/json",
  },
});

export default api;
