import axios from "axios";
import { requestHeaders } from "../utils/common-helper";
import router from "next/router";
import { toast } from "react-toastify";
export const postRequest: any = async (
  URL: any,
  formData?: any,
  isPublic: boolean = true,
  multipart?: boolean
) => {
  try {
    let error: any = null;
    const response: any = await axios
      .post(URL, formData, requestHeaders(isPublic, multipart))
      .catch((e) => {
        error = e.response;
        return error;
      });
    if (response && response.data && response.data.code) {
      const code: any = response.data.code;

      if (code === 401) {
        toast.error("Unauthenticated User");
        router.push("/login");
      }
    }
    return response;
  } catch (error) {}
};

export const getRequest: any = async (URL: any, isPublic: boolean = true) => {
  try {
    let error: any = null;
    const response: any = await axios
      .get(URL, requestHeaders(isPublic))
      .catch((e) => {
        error = e.response;
        return error;
      });
    if (response && response.data && response.data.code) {
      const code: any = response.data.code;

      if (code === 401) {
        router.push("/login");
      }
    }
    return response;
  } catch (error) {}
};

export const putRequest = async (
  URL: any,
  formData: any,
  isPublic: boolean = true,
  multipart?: boolean
) => {
  let error: any = null;
  const response: any = await axios
    .put(URL, formData, requestHeaders(isPublic, multipart))
    .catch((e) => {
      error = e.response;
      return error;
    });
  if (response && response.data && response.data.code) {
    const code: any = response.data.code;

    if (code === 401) {
      toast.error("Unauthenticated User");
      router.push("/login");
    }
  }
  return response;
};

export const patchRequest: any = async (
  URL: any,
  formData: any,
  isPublic: boolean = true
) => {
  try {
    let error: any = null;
    const response: any = await axios
      .patch(URL, formData, requestHeaders(isPublic))
      .catch((e) => {
        error = e.response;
        return error;
      });
    if (response && response.data && response.data.code) {
      const code: any = response.data.code;

      if (code === 401) {
        toast.error("Unauthenticated User");
        router.push("/login");
      }
    }
    return response;
  } catch (error) {}
};

export const deleteRequest: any = async (
  URL: any,
  isPublic: boolean = true
) => {
  try {
    let error: any = null;
    const response: any = await axios
      .delete(URL, requestHeaders(isPublic))
      .catch((e) => {
        error = e.response;
        return error;
      });
    if (response && response.data && response.data.code) {
      const code: any = response.data.code;

      if (code === 401) {
        toast.error("Unauthenticated User");
        router.push("/login");
      }
    }
    return response;
  } catch (error) {}
};
