"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.presentBalanceFetcherResponse = void 0;
const lodash_1 = __importDefault(require("lodash"));
const balance_utils_1 = require("../../../balance/balance.utils");
const contract_interface_1 = require("../../../position/contract.interface");
const getTotalsMeta = (balances) => {
    const filteredBalances = balances.filter(t => Math.abs(t.balanceUSD) >= 0.01);
    let totalAssetUSD = 0;
    let totalDebtUSD = 0;
    for (const balance of filteredBalances) {
        if (balance.type === contract_interface_1.ContractType.POSITION) {
            const [assets, debts] = lodash_1.default.partition(balance.tokens, t => t.balanceUSD > 0);
            totalAssetUSD += lodash_1.default.sumBy(assets, ({ balanceUSD }) => balanceUSD);
            totalDebtUSD += lodash_1.default.sumBy(debts, ({ balanceUSD }) => balanceUSD);
        }
        else {
            if (balance.balanceUSD > 0)
                totalAssetUSD += balance.balanceUSD;
            if (balance.balanceUSD < 0)
                totalDebtUSD += balance.balanceUSD;
        }
    }
    const totalUSD = totalAssetUSD - Math.abs(totalDebtUSD);
    return [
        {
            label: 'Total',
            value: totalUSD,
            type: 'dollar',
        },
        {
            label: 'Assets',
            value: totalAssetUSD,
            type: 'dollar',
        },
        {
            label: 'Debt',
            value: totalDebtUSD,
            type: 'dollar',
        },
    ];
};
const presentBalanceFetcherResponse = (products, meta = []) => {
    const storage = balance_utils_1.BALANCE_LOCALSTORAGE_FLAGS.getStore();
    const { includeZeroBalances } = storage !== null && storage !== void 0 ? storage : { includeZeroBalances: false };
    const nonZeroBalanceProducts = products
        .map(assetGroup => (Object.assign(Object.assign({}, assetGroup), { assets: assetGroup.assets.filter(b => !!b).filter(b => includeZeroBalances || Math.abs(b.balanceUSD) >= 0.01) })))
        .filter(assetGroup => assetGroup.assets.length > 0);
    const productsWithTotals = nonZeroBalanceProducts.map(assetGroup => {
        var _a;
        return (Object.assign(Object.assign({}, assetGroup), { meta: (_a = assetGroup.meta) !== null && _a !== void 0 ? _a : [] }));
    });
    const totalsMeta = getTotalsMeta(productsWithTotals.flatMap(assetGroup => assetGroup.assets));
    const metaWithTotals = [...meta, ...totalsMeta];
    return {
        products: productsWithTotals,
        meta: metaWithTotals,
    };
};
exports.presentBalanceFetcherResponse = presentBalanceFetcherResponse;
//# sourceMappingURL=balance-fetcher-response.present.js.map