import axios, { AxiosRequestConfig } from "axios";
import {
  API_GATE_WAY,
  ADMIN_API_PREFIX,
  REQUEST_TIMEOUT,
} from "@/constant/routes";
import { getAuth } from "@/pages/auth";
import { pageSize } from "@/constant/generalVariables";
import Cookies from "js-cookie";
import { postLogout } from "@/pages/auth/core/_requests";

const baseURL = API_GATE_WAY;
axios.defaults.baseURL = API_GATE_WAY;
axios.defaults.timeout = REQUEST_TIMEOUT;

const api = axios.create({
  baseURL,
  headers: {
    "Content-Type": "application/json",
  },
});

type HttpMethod =
  | "get"
  | "delete"
  | "head"
  | "options"
  | "post"
  | "put"
  | "patch"
  | "purge"
  | "link"
  | "unlink";

type RequestConfig = Exclude<AxiosRequestConfig, "method" | "url">;

export const httpGetRequest = <T>(endpoint: string, config?: RequestConfig) =>
  api<T>({
    method: "get",
    url: endpoint,
    ...config,
  });

export const httpPostRequest = <T>(
  endpoint: string,
  data: any,
  config?: RequestConfig
) =>
  api<T>({
    method: "post",
    url: endpoint,
    data,
    ...config,
  });

export const httpPutRequest = <T>(
  endpoint: string,
  data: any,
  config?: RequestConfig
) =>
  api<T>({
    method: "put",
    url: endpoint,
    data,
    ...config,
  });

export const httpPatchRequest = <T>(
  endpoint: string,
  data: any,
  config?: RequestConfig
) =>
  api<T>({
    method: "patch",
    url: endpoint,
    data,
    ...config,
  });

export const httpDeleteRequest = <T>(
  endpoint: string,
  config?: RequestConfig
) =>
  api<T>({
    method: "delete",
    url: endpoint,
    ...config,
  });

export const httpCustomRequest = <T>(
  url: string,
  method: HttpMethod,
  data?: any,
  config?: RequestConfig
) =>
  api<T>({
    method,
    url,
    data,
    ...config,
  });

export const httpUploader = async <T>(url: string, files: File[]) => {
  const formData = new FormData();
  files.forEach((file) => {
    formData.append("files", file, file.name);
  });

  const response = await httpPostRequest<T>(url, formData, {
    headers: {
      Accept: "text/plain",
      "Content-Type": "multipart/form-data",
    },
  });

  return response.data;
};

api.interceptors.request.use(async (config) => {
  const auth = await getAuth();
  if (auth?.token) {
    config.headers.Authorization = `Bearer ${auth.token}`;
  }
  return config;
});

api.interceptors.response.use(
  (response) => response,
  (error) => {
    const num = error.response.status;
    console.log("object");
    Cookies.remove("jwtToken");
    if ((num === 401 || num === 403) && location.pathname !== "/auth") {
      postLogout();
      window.location.replace(import.meta.env.VITE_APP_BASE_URL + "auth");
    } else {
      throw { ...error, message: error.response.data.title };
    }
  }
);

export const calculateTotalPages = (totalItemsCount: number | undefined) => {
  return totalItemsCount && pageSize
    ? Math.ceil(totalItemsCount / pageSize)
    : 1;
};

export function APIUrlGenerator(
  route: string,
  qry?: Record<string, string | number | null>,
  baseUrl?: string,
  useAdminPrefix: boolean = true
): string {
  const query = qry || {};
  const queryKeys = Object.keys(query);
  const prefix = useAdminPrefix ? `${ADMIN_API_PREFIX}/` : "";
  let apiUrl = `${baseUrl || API_GATE_WAY}/${prefix}${route}`;
  queryKeys.forEach((item, index) => {
    if (index === 0) {
      apiUrl += "?";
    }
    if (
      query[item] !== null &&
      query[item] !== undefined &&
      query[item] !== ""
    ) {
      apiUrl += `${item}=${query[item]}${
        index < queryKeys.length - 1 ? "&" : ""
      }`;
    }
  });
  return apiUrl;
}
