import axios, { AxiosInstance } from "axios";

export const createAxiosInstance = (baseURL: string): AxiosInstance => {
  const instance = axios.create({
    baseURL,
    timeout: 10000,
    headers: {
      "Content-Type": "application/json",
    },
  });

  instance.interceptors.request.use((config) => {
    const token = localStorage.getItem("token");
    const lang = localStorage.getItem("selectedLanguage") || "en";
    if (lang) {
      config.headers["Accept-Language"] = lang;
    }
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });

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

  return instance;
};
