import axios from "axios";
import Cookies from "js-cookie";
import { login } from "../auth";

const baseURL = "https://netidhub.com/api/";

const refreshToken = Cookies.get("refresh_token");

const axiosInterceptorInstance = axios.create({
  baseURL,
  headers: {
    "content-type": "application/json",
  },
});

// Request interceptor
axiosInterceptorInstance.interceptors.request.use(
  (config) => {
    console.log("Config interceptor : ", config);
    const accessToken = Cookies.get("access_token");
    if (accessToken) {
      if (config.headers)
        config.headers.Authorization = "Bearer " + accessToken;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor
axiosInterceptorInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async function (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const data = {
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        client_id: "mediahub-app",
      };
      console.log("refresh token ", data);
      const res = await login(data);
      if (res?.error) {
        Object.keys(Cookies.get()).forEach((cookieName) => {
          Cookies.remove(cookieName);
        });
      } else {
        const { access_token } = res?.data;
        const { refresh_token } = res?.data;
        if (access_token) {
          Cookies.set("access_token", access_token);
          Cookies.set("refresh_token", refresh_token);
        }
      }

      return axiosInterceptorInstance(originalRequest);
    }

    return Promise.reject(error);
  }
);

export default axiosInterceptorInstance;
