import useSWRMutation, { MutationFetcher, SWRMutationConfiguration, SWRMutationResponse } from "swr/mutation";
import { Key, NetworkError } from "../../swr";
import { blip } from "utils";
import { useMemo } from "react";

const defaultErrorHandler = (error: Error) => {
  const isNetworkError = error instanceof NetworkError;
  if (isNetworkError) {
    blip.error(error.serverError.message || error.message);
    return;
  }
  blip.error(error.message);
};

function useGuardedMutation<
  Data = any,
  Error = any,
  SWRMutationKey extends Key = Key,
  ExtraArg = never,
  SWRData = Data
>(
  key: SWRMutationKey,
  fetcher: MutationFetcher<Data, SWRMutationKey, ExtraArg>,
  options?: SWRMutationConfiguration<Data, Error, SWRMutationKey, ExtraArg, SWRData> & { throwOnError?: boolean }
): SWRMutationResponse<Data, Error, SWRMutationKey, ExtraArg> {
  const opts = useMemo(
    () =>
      ({
        ...options,
        onError: options?.onError ?? defaultErrorHandler,
        throwOnError: options?.throwOnError ?? false
      } as SWRMutationConfiguration<Data, Error, SWRMutationKey, ExtraArg, SWRData>),
    [options]
  );

  return useSWRMutation<Data, Error, SWRMutationKey, ExtraArg, SWRData>(key, fetcher, opts);
}

export default useGuardedMutation;
