import { deleteUserAuthData } from "@/actions/cookies";
import useUserStore from "@/store/useUserStore";
import axios, { AxiosInstance } from "axios";
import { redirect } from "next/navigation";
const Axios: AxiosInstance = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL + "/api",
  // timeout: 10000,
  params: {}, // do not remove this, its added to add params later in the config
});

// Add a request interceptor
Axios.interceptors.request.use(
  function (config) {
    const { data } = useUserStore.getState();
    if (data) {
      console.log(data, " axios");
      config.headers.Authorization = "Bearer " + data?.tokens?.access;
      // config.headers["ngrok-skip-browser-warning"] = "allow";
    }
    //
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
Axios.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  function (error) {
    if (error.response.status === 401) {
      const { setLogout } = useUserStore.getState();
      deleteUserAuthData();
      setLogout();
      // window.location = "/login" as any;
    }

    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

export default Axios;
