import { isNil } from 'lodash';

const isResponseCTError = (error) => {
  return typeof error === "object" && error !== null && ("code" in error || "message" in error || "details" in error);
};
const handleResponseCTError = (error) => {
  var _a;
  if ("details" in error && ((_a = error.details) == null ? void 0 : _a.length)) {
    return error.details.map((detail) => ({
      code: detail.reason,
      message: detail.message,
      params: detail.params
    }));
  } else if ("code" in error) {
    const code = error.code;
    if (!isNil(code)) {
      return [{ code, params: error.params }];
    }
  }
  if ("message" in error && typeof error.message === "string") {
    return [{ message: error.message }];
  }
  return [{ message: String(error) }];
};
const isAxiosCTError = (error) => {
  return typeof error === "object" && error !== null && "isAxiosError" in error && error.isAxiosError === true;
};
const handleAxiosCTError = (error) => {
  var _a;
  if ((_a = error.response) == null ? void 0 : _a.data) {
    const responseData = error.response.data;
    if (responseData && typeof responseData === "object") {
      const respError = handleResponseCTError(responseData);
      if (respError.length) {
        return respError;
      }
    }
  }
  return [{ code: `AXIOS_${error.code}` }];
};
const parseCTError = (error) => {
  if (typeof error === "object" && error !== null) {
    if (isAxiosCTError(error)) {
      return handleAxiosCTError(error);
    }
    if (isResponseCTError(error)) {
      return handleResponseCTError(error);
    }
    try {
      return [{ message: JSON.stringify(error) }];
    } catch (e) {
      return [{ message: String(error) }];
    }
  }
  return [{ message: String(error) }];
};

export { handleAxiosCTError, handleResponseCTError, isAxiosCTError, isResponseCTError, parseCTError };
