import axios from "axios";
import { postSignIn } from "../master-user";
import Cookies from "js-cookie";
import { API_BASE_URL } from "./api-base-url";

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

const axiosInterceptorInstance = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    "Content-Type": "application/json",
    "X-Client-Key": "9ca7f706-a8b0-4520-b467-5e8321df36fb",
  },
  withCredentials: true,
});

// Request interceptor
axiosInterceptorInstance.interceptors.request.use(
  (config) => {
    // Default instance uses application/json; FormData must not use JSON or File becomes {}.
    if (config.data instanceof FormData) {
      config.headers.delete("Content-Type");
    }
    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) => {
    console.log("Response interceptor : ", response);
    return response;
  },
  async function (error) {
    console.log("Error interceptor : ", error.response.status);
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const data = {
        grantType: "refresh_token",
        refreshToken: refreshToken,
        clientId: "mediahub-app",
      };
      console.log("refresh token ", data);
      const res = await postSignIn(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;
