import { showSnackbar } from "../../utils/showSnackbar";
import { LOADING_END } from "../redux/slices/appSlice";
import { LOG_OUT } from "../redux/slices/userSlice";
import { store } from "../redux/store";
import camelize from "camelize";

export function SetupAxios(axios) {
  const updateBaseUrl = () => {
    const userPath = store.getState().userSlice.userPath;
    axios.defaults.baseURL = userPath;
  };

  updateBaseUrl();

  const unsubscribe = store.subscribe(() => {
    const currentUserPath = store.getState().userSlice.userPath;
    if (currentUserPath !== axios.defaults.baseURL) {
      updateBaseUrl();
    }
  });

  axios.interceptors.request.use(
    (config) => {
      const {
        userSlice: { authToken },
      } = store.getState();
      if (authToken) {
        config.headers.Authorization = `Bearer ${authToken}`;
        config.headers.Accept = "application/json";
      } else {
        config.headers.Authorization = "Bearer null";
      }
      return config;
    },
    (err) => Promise.reject(err)
  );

  axios.interceptors.response.use(
    (response) => camelize(response),
    (error) => {
      if (error.response && error.response.status === 401) {
        showSnackbar("مدت زمان فعالیت شما به اتمام رسیده است.", "error");
        store.dispatch(LOADING_END());
        setTimeout(() => {
          store.dispatch(LOG_OUT());
        }, 3000);
      }
      return Promise.reject(error);
    }
  );

  return unsubscribe;
}
