import { Toast } from "native-base";
import { setRefreshedNewToken } from "./authentication";

/**
 * Display a toast for axios errors with optional custom message
 */
const axiosErrorMessage = (customMessage: string, error: any): string => {
  let errorMessage = customMessage + " ";

  if (error?.message) {
    errorMessage += error.message;
  }

  if (error?.response) {
    const { status, data } = error.response;

    if (status === 401) {
      setRefreshedNewToken();
      return "";
    }

    if (data?.message) {
      errorMessage += " Something went wrong at the server: " + data.message;
    }

    if (data?.msg) {
      errorMessage += " Something went wrong at the server: " + data.msg;
    }

    if (status === 404) {
      errorMessage += " Server not found. Server is busy or down.";
    }
  } else if (error?.request) {
    errorMessage = "Something went wrong while processing your request from your device: ";
    if (error.request._response) {
      errorMessage += error.request._response;
    }
  }

  Toast.show({
    title: "Error",
    description: errorMessage,
    placement: "bottom",
    duration: 3000,
    bgColor: "red.500",
  });

  return errorMessage;
};

/**
 * Return axios error message without showing toast
 */
const getErrorMessage = (error: any): string => {
  let errorMessage = " ";

  if (error?.response) {
    const { status, data } = error.response;

    if (data?.message) {
      errorMessage += data.message;
    }
    if (data?.msg) {
      errorMessage += data.msg;
    }
    if (status === 404) {
      errorMessage += " Server not found. Server is busy or down.";
    }
  } else if (error?.request) {
    errorMessage = "Something went wrong while processing your request from your device: ";
    if (error.request._response) {
      errorMessage += error.request._response;
    }
  }

  return errorMessage;
};

export { axiosErrorMessage, getErrorMessage };
