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

const authInstance = axios.create({
  baseURL: "https://wn.krbl.ru",
});

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: "https://wn.krbl.ru",
  });
  instance.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${localStorage.getItem("token")}`;
    config.headers["X-Language"] = language;
    return config;
  });
  return instance;
};

export { authInstance, languageInstance };
