import axios, { AxiosError, AxiosResponse, AxiosInstance } from "axios";

type ErrorHandler = (error: AxiosError) => Promise<never> | void;

const appUrl: string | undefined = process.env.REACT_APP_API_URL;

const axiosInstance: AxiosInstance = axios.create({
  baseURL: appUrl,
});

const errorHandler: ErrorHandler = (error) => {
  if (error.response?.status === 401) {
    // window.location.href = "/";
  } else {
    return Promise.reject(error?.response || "Something went wrong!");
  }
};

axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => response,
  (error: AxiosError) => errorHandler(error)
);

export default axiosInstance;
