import axios, { AxiosRequestConfig } from "axios";
import { getToken } from "./func";

const orvalAxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
});

orvalAxiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    return Promise.reject(error);
  }
);

orvalAxiosInstance.interceptors.request.use(async (config) => {
  const token = getToken();

  config.headers["Content-Type"] = "application/json";
  config.headers["Accept"] = "application/json";

  if (token) {
    config.headers["Authorization"] = `Bearer ${token}`;
  }

  const businessId = localStorage.getItem(import.meta.env.VITE_WORKSPACE_ID);
  if (businessId) {
    config.headers["x-business-id"] = businessId;
  }

  return config;
});

export const customAxiosInstance = <T = unknown>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> => {
  const source = axios.CancelToken.source();
  const promise = orvalAxiosInstance({
    ...config,
    ...options,
    cancelToken: source.token,
  }).then(({ data }) => data);

  // @ts-expect-error - Adding cancel method to promise
  promise.cancel = () => {
    source.cancel("Query was cancelled");
  };

  return promise;
};
