// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var CreateTrexSuiteBondCommandHandler_1;
import { InvalidRequest } from '../../error/InvalidRequest';
import { CommandHandler } from '../../../../../core/decorator/CommandHandlerDecorator';
import { lazyInject } from '../../../../../core/decorator/LazyInjectDecorator';
import ContractId from '../../../../../domain/context/contract/ContractId';
import { Security } from '../../../../../domain/context/security/Security';
import AccountService from '../../../../service/account/AccountService';
import TransactionService from '../../../../service/transaction/TransactionService';
import { MirrorNodeAdapter } from '../../../../../port/out/mirror/MirrorNodeAdapter';
import EvmAddress from '../../../../../domain/context/contract/EvmAddress';
import { BondDetails } from '../../../../../domain/context/bond/BondDetails';
import BigDecimal from '../../../../../domain/context/shared/BigDecimal';
import ContractService from '../../../../service/contract/ContractService';
import { MissingRegulationType } from '../../../../../domain/context/factory/error/MissingRegulationType';
import { MissingRegulationSubType } from '../../../../../domain/context/factory/error/MissingRegulationSubType';
import { EVM_ZERO_ADDRESS } from '../../../../../core/Constants';
import { CreateTrexSuiteBondCommand, CreateTrexSuiteBondCommandResponse, } from './CreateTrexSuiteBondCommand';
import { CreateTrexSuiteBondCommandError } from './error/CreateTrexSuiteBondError';
import { TrexClaimDetails, TrexTokenDetailsAts, } from '../../../../../domain/context/factory/TRexFactory';
import ValidationService from '../../../../service/validation/ValidationService';
let CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler_1 = class CreateTrexSuiteBondCommandHandler {
    constructor(accountService, transactionService, mirrorNodeAdapter, contractService, validationService) {
        this.accountService = accountService;
        this.transactionService = transactionService;
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.contractService = contractService;
        this.validationService = validationService;
    }
    async execute(command) {
        let res;
        try {
            const { salt, owner, irs, onchainId, irAgents, tokenAgents, compliancesModules, complianceSettings, claimTopics, issuers, issuerClaims, security, currency, nominalValue, nominalValueDecimals, startingDate, maturityDate, factory, resolver, configId, configVersion, diamondOwnerAccount, proceedRecipientsIds, proceedRecipientsData, externalPauses, externalControlLists, externalKycLists, compliance, identityRegistry, } = command;
            if (!security.regulationType) {
                throw new MissingRegulationType();
            }
            if (!security.regulationsubType) {
                throw new MissingRegulationSubType();
            }
            if (!salt || salt.length === 0) {
                throw new InvalidRequest('Salt not found in request');
            }
            this.validationService.checkTrexTokenSaltExists(factory.toString(), salt);
            const trexTokenDetails = new TrexTokenDetailsAts({
                owner,
                irs,
                onchainId,
                irAgents,
                tokenAgents,
                compliancesModules,
                complianceSettings,
            });
            const claimDetails = new TrexClaimDetails({
                claimTopics,
                issuers,
                issuerClaims,
            });
            const factoryEvmAddress = await this.contractService.getContractEvmAddress(factory.toString());
            const [externalPausesEvmAddresses, externalControlListsEvmAddresses, externalKycListsEvmAddresses,] = await Promise.all([
                this.contractService.getEvmAddressesFromHederaIds(externalPauses),
                this.contractService.getEvmAddressesFromHederaIds(externalControlLists),
                this.contractService.getEvmAddressesFromHederaIds(externalKycLists),
            ]);
            let proceedRecipientsEvmAddresses = [];
            if (proceedRecipientsIds)
                proceedRecipientsEvmAddresses = await Promise.all(proceedRecipientsIds.map(async (id) => await this.accountService.getAccountEvmAddress(id)));
            const diamondOwnerAccountEvmAddress = await this.accountService.getAccountEvmAddress(diamondOwnerAccount);
            const resolverEvmAddress = await this.contractService.getContractEvmAddress(resolver.toString());
            const complianceEvmAddress = compliance
                ? await this.contractService.getContractEvmAddress(compliance)
                : new EvmAddress(EVM_ZERO_ADDRESS);
            const identityRegistryAddress = identityRegistry
                ? await this.contractService.getContractEvmAddress(identityRegistry)
                : new EvmAddress(EVM_ZERO_ADDRESS);
            const handler = this.transactionService.getHandler();
            const bondInfo = new BondDetails(currency, BigDecimal.fromString(nominalValue), nominalValueDecimals, parseInt(startingDate), parseInt(maturityDate));
            res = await handler.createTrexSuiteBond(salt, trexTokenDetails.owner, trexTokenDetails.irs, trexTokenDetails.onchainId, trexTokenDetails.irAgents, trexTokenDetails.tokenAgents, trexTokenDetails.compliancesModules, trexTokenDetails.complianceSettings, claimDetails.claimTopics, claimDetails.issuers, claimDetails.issuerClaims, new Security(security), bondInfo, factoryEvmAddress, resolverEvmAddress, configId, configVersion, complianceEvmAddress, identityRegistryAddress, diamondOwnerAccountEvmAddress, proceedRecipientsEvmAddresses, proceedRecipientsData, externalPausesEvmAddresses, externalControlListsEvmAddresses, externalKycListsEvmAddresses, factory.toString());
            const contractAddress = await this.transactionService.getTransactionResult({
                res,
                result: res.response?._token,
                className: CreateTrexSuiteBondCommandHandler_1.name,
                position: 0,
                numberOfResultsItems: 1,
            });
            const contractId = await this.mirrorNodeAdapter.getHederaIdfromContractAddress(contractAddress);
            return Promise.resolve(new CreateTrexSuiteBondCommandResponse(new ContractId(contractId), res.id));
        }
        catch (error) {
            if (res?.response == 1) {
                return Promise.resolve(new CreateTrexSuiteBondCommandResponse(new ContractId('0.0.0'), res.id));
            }
            throw new CreateTrexSuiteBondCommandError(error);
        }
    }
};
CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler_1 = __decorate([
    CommandHandler(CreateTrexSuiteBondCommand),
    __param(0, lazyInject(AccountService)),
    __param(1, lazyInject(TransactionService)),
    __param(2, lazyInject(MirrorNodeAdapter)),
    __param(3, lazyInject(ContractService)),
    __param(4, lazyInject(ValidationService)),
    __metadata("design:paramtypes", [AccountService,
        TransactionService,
        MirrorNodeAdapter,
        ContractService,
        ValidationService])
], CreateTrexSuiteBondCommandHandler);
export { CreateTrexSuiteBondCommandHandler };
