"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 CreateBondFixedRateCommandHandler_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateBondFixedRateCommandHandler = void 0;
const CreateBondFixedRateCommand_1 = require("./CreateBondFixedRateCommand");
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 BigDecimal_1 = __importDefault(require("../../../../../domain/context/shared/BigDecimal"));
const ContractService_1 = __importDefault(require("../../../../service/contract/ContractService"));
const CreateBondFixedRateCommandError_1 = require("./error/CreateBondFixedRateCommandError");
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 BondFixedRateDetails_1 = require("../../../../../domain/context/bond/BondFixedRateDetails");
let CreateBondFixedRateCommandHandler = CreateBondFixedRateCommandHandler_1 = class CreateBondFixedRateCommandHandler {
    accountService;
    transactionService;
    mirrorNodeAdapter;
    contractService;
    constructor(accountService, transactionService, mirrorNodeAdapter, contractService) {
        this.accountService = accountService;
        this.transactionService = transactionService;
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.contractService = contractService;
    }
    async execute(command) {
        let res;
        try {
            const { security, currency, nominalValue, nominalValueDecimals, startingDate, maturityDate, factory, resolver, configId, configVersion, diamondOwnerAccount, externalPausesIds, externalControlListsIds, externalKycListsIds, complianceId, identityRegistryId, proceedRecipientsIds, proceedRecipientsData, } = command;
            //TODO: Boy scout: remove request validations and adjust test
            if (!factory) {
                throw new InvalidRequest_1.InvalidRequest("Factory not found in request");
            }
            if (!resolver) {
                throw new InvalidRequest_1.InvalidRequest("Resolver not found in request");
            }
            if (!configId) {
                throw new InvalidRequest_1.InvalidRequest("Config Id not found in request");
            }
            if (configVersion === undefined) {
                throw new InvalidRequest_1.InvalidRequest("Config Version not found in request");
            }
            if (!security.regulationType) {
                throw new MissingRegulationType_1.MissingRegulationType();
            }
            if (!security.regulationsubType) {
                throw new MissingRegulationSubType_1.MissingRegulationSubType();
            }
            const diamondOwnerAccountEvmAddress = await this.accountService.getAccountEvmAddress(diamondOwnerAccount);
            const factoryEvmAddress = await this.contractService.getContractEvmAddress(factory.toString());
            const resolverEvmAddress = await this.contractService.getContractEvmAddress(resolver.toString());
            const [externalPausesEvmAddresses, externalControlListsEvmAddresses, externalKycListsEvmAddresses] = await Promise.all([
                this.contractService.getEvmAddressesFromHederaIds(externalPausesIds),
                this.contractService.getEvmAddressesFromHederaIds(externalControlListsIds),
                this.contractService.getEvmAddressesFromHederaIds(externalKycListsIds),
            ]);
            let proceedRecipientsEvmAddresses = [];
            if (proceedRecipientsIds)
                proceedRecipientsEvmAddresses = await Promise.all(proceedRecipientsIds.map(async (id) => await this.accountService.getAccountEvmAddress(id)));
            const complianceEvmAddress = complianceId
                ? await this.contractService.getContractEvmAddress(complianceId)
                : new EvmAddress_1.default(Constants_1.EVM_ZERO_ADDRESS);
            const identityRegistryAddress = identityRegistryId
                ? await this.contractService.getContractEvmAddress(identityRegistryId)
                : new EvmAddress_1.default(Constants_1.EVM_ZERO_ADDRESS);
            const handler = this.transactionService.getHandler();
            const bondFixedRateInfo = new BondFixedRateDetails_1.BondFixedRateDetails(currency, BigDecimal_1.default.fromString(nominalValue), nominalValueDecimals, parseInt(startingDate), parseInt(maturityDate), command.rate, command.rateDecimals);
            res = await handler.createBondFixedRate(new Security_1.Security(security), bondFixedRateInfo, factoryEvmAddress, resolverEvmAddress, configId, configVersion, complianceEvmAddress, identityRegistryAddress, externalPausesEvmAddresses, externalControlListsEvmAddresses, externalKycListsEvmAddresses, diamondOwnerAccountEvmAddress, proceedRecipientsEvmAddresses, proceedRecipientsData, factory.toString());
            const contractAddress = await this.transactionService.getTransactionResult({
                res,
                result: res.response?.bondAddress,
                className: CreateBondFixedRateCommandHandler_1.name,
                position: 0,
                numberOfResultsItems: 1,
            });
            const contractId = await this.mirrorNodeAdapter.getHederaIdfromContractAddress(contractAddress);
            return Promise.resolve(new CreateBondFixedRateCommand_1.CreateBondFixedRateCommandResponse(new ContractId_1.default(contractId), res.id));
        }
        catch (error) {
            if (res?.response == 1) {
                return Promise.resolve(new CreateBondFixedRateCommand_1.CreateBondFixedRateCommandResponse(new ContractId_1.default("0.0.0"), res.id));
            }
            throw new CreateBondFixedRateCommandError_1.CreateBondFixedRateCommandError(error);
        }
    }
};
exports.CreateBondFixedRateCommandHandler = CreateBondFixedRateCommandHandler;
exports.CreateBondFixedRateCommandHandler = CreateBondFixedRateCommandHandler = CreateBondFixedRateCommandHandler_1 = __decorate([
    (0, CommandHandlerDecorator_1.CommandHandler)(CreateBondFixedRateCommand_1.CreateBondFixedRateCommand),
    __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)),
    __metadata("design:paramtypes", [AccountService_1.default,
        TransactionService_1.default,
        MirrorNodeAdapter_1.MirrorNodeAdapter,
        ContractService_1.default])
], CreateBondFixedRateCommandHandler);
