"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const account_1 = require("../../account");
exports.default = ({ account, operation, transaction, swap, swapId, }) => {
    const { exchange, exchangeRate } = swap;
    const { fromAccount, toAccount, toParentAccount } = exchange;
    const mainToAccount = (0, account_1.getMainAccount)(toAccount, toParentAccount);
    const toCurrency = (0, account_1.getAccountCurrency)(toAccount);
    const fromCurrency = (0, account_1.getAccountCurrency)(fromAccount);
    const subAccounts = account.type === "Account" && account.subAccounts;
    const tokenId = toCurrency.type === "TokenCurrency" ? toCurrency.id : undefined;
    const isFromToken = fromCurrency.type === "TokenCurrency";
    const operationId = isFromToken && operation.subOperations && operation.subOperations.length > 0
        ? operation.subOperations[0].id
        : operation.id;
    const toAmount = transaction.amount.times(exchangeRate.magnitudeAwareRate);
    const swapOperation = {
        status: "pending",
        provider: exchangeRate.provider,
        operationId,
        swapId,
        // NB We store the reciever main account + tokenId in case the token account doesn't exist yet.
        receiverAccountId: mainToAccount.id,
        tokenId,
        fromAmount: transaction.amount,
        toAmount,
    };
    return isFromToken && subAccounts
        ? {
            ...account,
            subAccounts: subAccounts.map((a) => {
                const subAccount = {
                    ...a,
                    swapHistory: [...a.swapHistory, swapOperation],
                };
                return a.id === fromAccount?.id ? subAccount : a;
            }),
        }
        : { ...account, swapHistory: [...account.swapHistory, swapOperation] };
};
//# sourceMappingURL=addToSwapHistory.js.map