"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.inferError = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const __1 = require("..");
const errors_1 = require("../../../errors");
const formatCurrencyUnit_1 = require("@ledgerhq/coin-framework/currencies/formatCurrencyUnit");
function inferError(response, unitFrom) {
    const isAMinMaxError = ("minAmountFrom" in response || "maxAmountFrom" in response) &&
        "amountRequested" in response &&
        (!!response.minAmountFrom || !!response.maxAmountFrom) &&
        !!response.amountRequested;
    const isADexMinMaxError = (!("minAmountFrom" in response) || !("maxAmountFrom" in response)) &&
        "errorCode" in response &&
        response.providerType === "DEX" &&
        response.errorCode !== 300;
    const isAnErrorCodeMessageError = "errorCode" in response && "errorMessage" in response;
    if (isADexMinMaxError) {
        return new errors_1.SwapExchangeRateAmountTooLowOrTooHigh(undefined, {
            message: "",
        });
    }
    if (isAMinMaxError) {
        const isTooSmall = (0, bignumber_js_1.default)(response.amountRequested).lt(response.minAmountFrom);
        const minOrMaxError = isTooSmall
            ? {
                error: errors_1.SwapExchangeRateAmountTooLow,
                amount: response.minAmountFrom,
                key: "minAmountFromFormatted",
            }
            : {
                error: errors_1.SwapExchangeRateAmountTooHigh,
                amount: response.maxAmountFrom,
                key: "maxAmountFromFormatted",
            };
        return new minOrMaxError.error(undefined, {
            [minOrMaxError.key]: (0, formatCurrencyUnit_1.formatCurrencyUnit)(unitFrom, new bignumber_js_1.default(minOrMaxError?.amount).times((0, bignumber_js_1.default)(10).pow(unitFrom.magnitude)), {
                alwaysShowSign: false,
                disableRounding: true,
                showCode: true,
            }),
            amount: new bignumber_js_1.default(minOrMaxError.amount),
        });
    }
    if (isAnErrorCodeMessageError) {
        return (0, __1.getSwapAPIError)(response.errorCode, response.errorMessage);
    }
    return new errors_1.SwapGenericAPIError();
}
exports.inferError = inferError;
//# sourceMappingURL=inferRatesError.js.map