import { useCallback, useMemo } from "react";
import { useToast } from "../contexts/ToastContext";

const useHttpRequest = () => {
  const { error } = useToast();

  const handleError = useCallback(
    (err) => {
      let message;
      switch (err?.statusCode) {
        case 500:
          message = "Internal server error.";
          break;

        case 404:
          message = err.serverMessage;
          break;

        case 401:
          message = `Unauthorized: ${err.serverMessage}`;
          break;

        default:
          message = "An unexpected error has occurred.";
      }

      error(message);
    },
    [error]
  );

  const defaultOptions = useMemo(
    () => ({
      onStart: () => {},
      onCompleted: () => {},
      onError: handleError
    }),
    [handleError]
  );

  const exec = useCallback(
    async (request, options) => {
      const internalOptions = { ...defaultOptions, ...options };
      const { onStart, onCompleted, onError } = internalOptions;

      try {
        onStart();
        const result = await request();
        onCompleted(result);
        return result;
      } catch (error) {
        onError(error);
        throw error;
      }
    },
    [defaultOptions]
  );

  return {
    exec
  };
};

export default useHttpRequest;
