"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genericGetAccountShape = void 0;
const index_1 = require("@ledgerhq/coin-framework/account/index");
const jsHelpers_1 = require("@ledgerhq/coin-framework/bridge/jsHelpers");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const alpaca_1 = require("./alpaca");
const utils_1 = require("./utils");
function genericGetAccountShape(network, kind) {
    return async (info) => {
        try {
            const { address, initialAccount, currency, derivationMode } = info;
            const accountId = (0, index_1.encodeAccountId)({
                type: "js",
                version: "2",
                currencyId: currency.id,
                xpubOrAddress: address,
                derivationMode,
            });
            const blockInfo = await (0, alpaca_1.getAlpacaApi)(network, kind).lastBlock();
            const balanceRes = await (0, alpaca_1.getAlpacaApi)(network, kind).getBalance(address);
            // FIXME: fix type Balance -> check "native" balance
            // is balance[0] always the native ?
            const balance = (0, bignumber_js_1.default)(balanceRes[0].value.toString());
            let spendableBalance;
            if (balanceRes[0]?.locked) {
                spendableBalance = bignumber_js_1.default.max(balance.minus((0, bignumber_js_1.default)(balanceRes[0].locked.toString())), (0, bignumber_js_1.default)(0));
            }
            else {
                spendableBalance = initialAccount?.spendableBalance || balance;
            }
            const oldOperations = initialAccount?.operations || [];
            const blockHeight = oldOperations.length ? (oldOperations[0].blockHeight ?? 0) + 1 : 0;
            const [newOperations] = await (0, alpaca_1.getAlpacaApi)(network, kind).listOperations(address, {
                minHeight: blockHeight,
            });
            const operations = (0, jsHelpers_1.mergeOps)(oldOperations, newOperations.map(op => (0, utils_1.adaptCoreOperationToLiveOperation)(accountId, op)));
            return {
                id: accountId,
                xpub: address,
                blockHeight: blockInfo.height || initialAccount?.blockHeight,
                balance,
                spendableBalance,
                operations,
                operationsCount: operations.length,
            };
        }
        catch (e) {
            console.error("Error in getAccountShape", e);
            throw e;
        }
    };
}
exports.genericGetAccountShape = genericGetAccountShape;
//# sourceMappingURL=getAccountShape.js.map