import Axios from "axios";
import { showErrorToast } from "../components/customToast";

const pendingRequests = new Map();

const axios = Axios.create({
  baseURL:
    window.location.hostname.includes("staging") ||
    window.location.hostname.includes("localhost")
      ? "https://dev-117782726-api.learngual.com"
      : "https://api.learngual.com",
});

axios.interceptors.request.use(
  async (config) => {
    // preventing duplicate requests >> starts
    const requestKey = config.url;

    if (pendingRequests.has(requestKey)) {
      console.log("preventing::", requestKey);
      return Promise.reject(new Axios.Cancel("Duplicate request"));
    }

    const source = Axios.CancelToken.source();
    pendingRequests.set(requestKey, source);
    config.cancelToken = source.token;
    // preventing duplicate requests ends >>

    const cookies = document.cookie;
    const cookieArray = cookies.split(";");

    let token;
    let defaultAccountID;

    for (let i = 0; i < cookieArray.length; i++) {
      const cookie = cookieArray[i].trim();

      if (cookie.startsWith("access=")) {
        token = cookie.substring("access=".length, cookie.length);
        break;
      }
    }

    for (let i = 0; i < cookieArray.length; i++) {
      const cookie = cookieArray[i].trim();
      if (cookie.startsWith("defaultAccountID=")) {
        defaultAccountID = cookie.substring(
          "defaultAccountID=".length,
          cookie.length
        );
        break;
      }
    }

    // Add additional logic to check if the current request path matches any authRoutes
    // const currentPath = config.url;
    // const matchedRoute = authRoutes.find((route) =>
    //   currentPath.includes(route)
    // );
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      const date = new Date();
      const params = {
        // ...config.params,
        // // _tz: date.getTimezoneOffset() / 60,
        // _account: defaultAccountID,
        // //

        _account: defaultAccountID,
        ...config.params,
      };
      config.params = params;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 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
//     if (response.status === 403) {
//       // Handle unauthorized access
//       toast.error("Unauthorized");
//       //console.log(response.status, "+++++++REPONSE ====");
//     }
//     return response;
//   },
//   function (error) {
//     // Any status codes that fall outside the range of 2xx cause this function to trigger
//     // Do something with response error
//     return Promise.reject(error);
//   }
// );

axios.interceptors.response.use(
  (response) => {
    pendingRequests.delete(response.config.url);
    console.log("deleting", response.config.url);
    if (
      response.status === 207 &&
      !window.location.host.includes("staging") &&
      !window.location.host.includes("local")
    ) {
      window.location.href = "/auth/account-type";
    }
    return response;
  },
  (err) => {
    if (err) {
      if (err.config) pendingRequests.delete(err.config.url);

      // If it's not a cancellation error, handle it as usual
      if (!Axios.isCancel(err)) {
        if (err.response?.status === 400) {
          showErrorToast(err?.response?.data?.detail || "Bad request");
        }
        return err;
      } else {
        return {};
      }
    }
  }
);

export default axios;
