import axios, { AxiosInstance } from "axios";
import { getWithExpiry } from "../logic/loigicUtils";

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 = getWithExpiry("token");
    const lang = getWithExpiry("selectedLanguage") || "en";
    config.headers["Content-Type"] = "application/json";
    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;
};
