"use strict";
// 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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var CreateTrexSuiteBondCommandHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateTrexSuiteBondCommandHandler = void 0;
const InvalidRequest_1 = require("../../error/InvalidRequest");
const CommandHandlerDecorator_1 = require("../../../../../core/decorator/CommandHandlerDecorator");
const LazyInjectDecorator_1 = require("../../../../../core/decorator/LazyInjectDecorator");
const ContractId_1 = __importDefault(require("../../../../../domain/context/contract/ContractId"));
const Security_1 = require("../../../../../domain/context/security/Security");
const AccountService_1 = __importDefault(require("../../../../service/account/AccountService"));
const TransactionService_1 = __importDefault(require("../../../../service/transaction/TransactionService"));
const MirrorNodeAdapter_1 = require("../../../../../port/out/mirror/MirrorNodeAdapter");
const EvmAddress_1 = __importDefault(require("../../../../../domain/context/contract/EvmAddress"));
const BondDetails_1 = require("../../../../../domain/context/bond/BondDetails");
const BigDecimal_1 = __importDefault(require("../../../../../domain/context/shared/BigDecimal"));
const ContractService_1 = __importDefault(require("../../../../service/contract/ContractService"));
const MissingRegulationType_1 = require("../../../../../domain/context/factory/error/MissingRegulationType");
const MissingRegulationSubType_1 = require("../../../../../domain/context/factory/error/MissingRegulationSubType");
const Constants_1 = require("../../../../../core/Constants");
const CreateTrexSuiteBondCommand_1 = require("./CreateTrexSuiteBondCommand");
const CreateTrexSuiteBondError_1 = require("./error/CreateTrexSuiteBondError");
const TRexFactory_1 = require("../../../../../domain/context/factory/TRexFactory");
const ValidationService_1 = __importDefault(require("../../../../service/validation/ValidationService"));
let CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler_1 = class CreateTrexSuiteBondCommandHandler {
    accountService;
    transactionService;
    mirrorNodeAdapter;
    contractService;
    validationService;
    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_1.MissingRegulationType();
            }
            if (!security.regulationsubType) {
                throw new MissingRegulationSubType_1.MissingRegulationSubType();
            }
            if (!salt || salt.length === 0) {
                throw new InvalidRequest_1.InvalidRequest("Salt not found in request");
            }
            this.validationService.checkTrexTokenSaltExists(factory.toString(), salt);
            const trexTokenDetails = new TRexFactory_1.TrexTokenDetailsAts({
                owner,
                irs,
                onchainId,
                irAgents,
                tokenAgents,
                compliancesModules,
                complianceSettings,
            });
            const claimDetails = new TRexFactory_1.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_1.default(Constants_1.EVM_ZERO_ADDRESS);
            const identityRegistryAddress = identityRegistry
                ? await this.contractService.getContractEvmAddress(identityRegistry)
                : new EvmAddress_1.default(Constants_1.EVM_ZERO_ADDRESS);
            const handler = this.transactionService.getHandler();
            const bondInfo = new BondDetails_1.BondDetails(currency, BigDecimal_1.default.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_1.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 CreateTrexSuiteBondCommand_1.CreateTrexSuiteBondCommandResponse(new ContractId_1.default(contractId), res.id));
        }
        catch (error) {
            if (res?.response == 1) {
                return Promise.resolve(new CreateTrexSuiteBondCommand_1.CreateTrexSuiteBondCommandResponse(new ContractId_1.default("0.0.0"), res.id));
            }
            throw new CreateTrexSuiteBondError_1.CreateTrexSuiteBondCommandError(error);
        }
    }
};
exports.CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler;
exports.CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler = CreateTrexSuiteBondCommandHandler_1 = __decorate([
    (0, CommandHandlerDecorator_1.CommandHandler)(CreateTrexSuiteBondCommand_1.CreateTrexSuiteBondCommand),
    __param(0, (0, LazyInjectDecorator_1.lazyInject)(AccountService_1.default)),
    __param(1, (0, LazyInjectDecorator_1.lazyInject)(TransactionService_1.default)),
    __param(2, (0, LazyInjectDecorator_1.lazyInject)(MirrorNodeAdapter_1.MirrorNodeAdapter)),
    __param(3, (0, LazyInjectDecorator_1.lazyInject)(ContractService_1.default)),
    __param(4, (0, LazyInjectDecorator_1.lazyInject)(ValidationService_1.default)),
    __metadata("design:paramtypes", [AccountService_1.default,
        TransactionService_1.default,
        MirrorNodeAdapter_1.MirrorNodeAdapter,
        ContractService_1.default,
        ValidationService_1.default])
], CreateTrexSuiteBondCommandHandler);
