import { languageStore, Language } from "@shared";
import axios, { AxiosError, InternalAxiosRequestConfig } from "axios";

const authInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
});

authInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
  config.headers["X-Language"] = languageStore.language ?? "ru";
  return config;
});

authInstance.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

const languageInstance = (language: Language) => {
  const instance = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
  });
  instance.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    config.headers["X-Language"] = language;
    return config;
  });
  return instance;
};

export { authInstance, languageInstance };
export { mobxFetch } from "./mobxFetch";
