"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchRates = exports.throwRateError = void 0;
const live_network_1 = __importDefault(require("@ledgerhq/live-network"));
const timeout_1 = require("../../const/timeout");
const axios_1 = __importDefault(require("axios"));
const errors_1 = require("@ledgerhq/errors");
const errors_2 = require("../../../../errors");
const enrichRatesResponse_1 = require("../../utils/enrichRatesResponse");
const isIntegrationTestEnv_1 = require("../../utils/isIntegrationTestEnv");
const fetchRates_mocks_1 = require("./__mocks__/fetchRates.mocks");
const __1 = require("../..");
const throwRateError = (response) => {
    // ranked errors so incases where all rates error we return
    // the highest priority error to the user.
    // lowest number is the highest rank.
    // highest number is lowest rank.
    const errorsRank = {
        SwapExchangeRateAmountTooLowOrTooHigh: 1,
        SwapExchangeRateAmountTooLow: 2,
        SwapExchangeRateAmountTooHigh: 3,
    };
    const filterLimitResponse = response.filter(rate => {
        const name = rate.error && rate.error["name"];
        return name && errorsRank[name];
    });
    if (!filterLimitResponse.length)
        throw new errors_2.SwapGenericAPIError();
    // get the highest ranked error and throw it.
    const initError = filterLimitResponse[0].error;
    const error = filterLimitResponse.reduce((acc, curr) => {
        const currError = curr.error;
        if (!acc || !currError || !acc["name"] || !currError["name"])
            return acc;
        const currErrorRank = errorsRank[currError["name"]];
        const accErrorRank = errorsRank[acc["name"]];
        if (currErrorRank <= accErrorRank) {
            if (currErrorRank === 1)
                return currError;
            const currErrorLimit = currError["amount"];
            const accErrorLimit = acc["amount"];
            // Get smallest amount supported
            if (currErrorRank === 2 &&
                currErrorLimit &&
                currErrorLimit.isLessThan(accErrorLimit || Infinity)) {
                return curr.error;
            }
            // Get highest amount supported
            if (currErrorRank === 3 &&
                currErrorLimit &&
                currErrorLimit.isGreaterThan(accErrorLimit || -Infinity)) {
                return curr.error;
            }
        }
        return acc;
    }, initError);
    throw error;
};
exports.throwRateError = throwRateError;
async function fetchRates({ providers, currencyFrom, toCurrencyId, unitTo, unitFrom, fromCurrencyAmount, }) {
    if ((0, isIntegrationTestEnv_1.isIntegrationTestEnv)()) {
        return Promise.resolve((0, enrichRatesResponse_1.enrichRatesResponse)((0, fetchRates_mocks_1.fetchRatesMock)(fromCurrencyAmount, currencyFrom), unitTo, unitFrom));
    }
    const url = new URL(`${(0, __1.getSwapAPIBaseURL)()}/rate`);
    const requestBody = {
        from: currencyFrom,
        to: toCurrencyId,
        amountFrom: fromCurrencyAmount,
        providers: providers,
    };
    const headers = (0, __1.getSwapUserIP)();
    try {
        const { data } = await (0, live_network_1.default)({
            method: "POST",
            url: url.toString(),
            timeout: timeout_1.DEFAULT_SWAP_TIMEOUT_MS,
            data: requestBody,
            ...(headers !== undefined ? { headers } : {}),
        });
        const filteredData = data.filter(response => ![300, 304, 306, 308].includes(response?.errorCode)); // remove backend only errors
        const enrichedResponse = (0, enrichRatesResponse_1.enrichRatesResponse)(filteredData, unitTo, unitFrom);
        const allErrored = enrichedResponse.every(res => !!res.error);
        if (allErrored) {
            (0, exports.throwRateError)(enrichedResponse);
        }
        // if some of the rates are successful then return those.
        return enrichedResponse
            .filter(res => !res.error)
            .sort((a, b) => b.toAmount.minus(a.toAmount).toNumber());
    }
    catch (e) {
        if (axios_1.default.isAxiosError(e)) {
            if (e.code === "ECONNABORTED") {
                // TODO: LIVE-8901 (handle request timeout)
            }
        }
        if (e instanceof errors_1.LedgerAPI4xx) {
            // TODO: LIVE-8901 (handle 4xx)
        }
        throw e;
    }
}
exports.fetchRates = fetchRates;
//# sourceMappingURL=fetchRates.js.map