"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetTransactionByIdUseCase = void 0;
const transaction_1 = require("../../../domain/entities/transaction");
const not_found_error_1 = require("../../../domain/errors/not-found-error");
const collectAddressIds = (tx) => {
    const ids = new Set();
    if (tx.from)
        ids.add(tx.from);
    if (tx.to)
        ids.add(tx.to);
    for (const path of tx.data) {
        if ('from' in path && path.from)
            ids.add(path.from);
        if ('to' in path && path.to)
            ids.add(path.to);
    }
    return Array.from(ids);
};
class GetTransactionByIdUseCase {
    transactionRepository;
    addressRepository;
    constructor(transactionRepository, addressRepository) {
        this.transactionRepository = transactionRepository;
        this.addressRepository = addressRepository;
    }
    async execute(id) {
        const transaction = await this.transactionRepository.findById(id);
        if (!transaction) {
            throw new not_found_error_1.NotFoundError('Transaction', id);
        }
        const addressIds = collectAddressIds(transaction);
        const addresses = await this.addressRepository.findByIds(addressIds);
        const addressMap = new Map(addresses.map(a => [a.id, a.address]));
        const dataWithAddresses = transaction.data.map(path => ({
            ...path,
            fromAddress: 'from' in path && path.from
                ? addressMap.get(path.from) ?? null
                : null,
            toAddress: 'to' in path && path.to ? addressMap.get(path.to) ?? null : null,
        }));
        return new transaction_1.Transaction(transaction.id, transaction.hash, transaction.status, transaction.block, transaction.networkId, transaction.timestamp, transaction.from, transaction.to, transaction.interactedWith, transaction.value, transaction.fee, transaction.gasPrice, transaction.gasLimit, transaction.method, dataWithAddresses, transaction.createdAt, transaction.updatedAt, transaction.from ? addressMap.get(transaction.from) ?? null : null, transaction.to ? addressMap.get(transaction.to) ?? null : null);
    }
}
exports.GetTransactionByIdUseCase = GetTransactionByIdUseCase;
//# sourceMappingURL=get-transaction-by-id.use-case.js.map