import axios from "axios";

const envUrl = import.meta.env.VITE_API_URL || "localhost";
const baseURL = envUrl.includes("://") ? envUrl : `http://${envUrl}`;
const isFullUrl =
  baseURL.includes("://") &&
  !envUrl.includes("localhost") &&
  !envUrl.includes("127.0.0.1");

const addAuthInterceptor = (instance) => {
  instance.interceptors.request.use((config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });
};

export const apiBaseURL = isFullUrl ? baseURL : `${baseURL}:8080`;
export const geoBaseURL = isFullUrl ? baseURL : `${baseURL}:6001`;
export const weatherBaseURL = isFullUrl ? baseURL : `${baseURL}:6002`;

export const getMediaUrl = (id) => {
  const token = localStorage.getItem("token");
  const base = `${apiBaseURL}/media/${id}/download`;
  return token ? `${base}?token=${token}` : base;
};

export const apiInstance = axios.create({ baseURL: apiBaseURL });
addAuthInterceptor(apiInstance);

export const geoInstance = axios.create({ baseURL: geoBaseURL });
addAuthInterceptor(geoInstance);

export const weatherInstance = axios.create({ baseURL: weatherBaseURL });
addAuthInterceptor(weatherInstance);
