"use strict";
// SPDX-License-Identifier: Apache-2.0
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const CreateBondFixedRateCommandHandler_1 = require("./CreateBondFixedRateCommandHandler");
const ts_jest_1 = require("@golevelup/ts-jest");
const BondFixedRateFixture_1 = require("../../../../../../__tests__/fixtures/bond/BondFixedRateFixture");
const CreateBondFixedRateCommand_1 = require("./CreateBondFixedRateCommand");
const BigDecimal_1 = __importDefault(require("../../../../../domain/context/shared/BigDecimal"));
const DataFixture_1 = require("../../../../../../__tests__/fixtures/shared/DataFixture");
const EvmAddress_1 = __importDefault(require("../../../../../domain/context/contract/EvmAddress"));
const CreateBondFixedRateCommandError_1 = require("./error/CreateBondFixedRateCommandError");
const BaseError_1 = require("../../../../../core/error/BaseError");
describe("CreateBondFixedRateCommandHandler", () => {
    let handler;
    let command;
    const transactionServiceMock = (0, ts_jest_1.createMock)();
    const mirrorNodeAdapterMock = (0, ts_jest_1.createMock)();
    const accountServiceMock = (0, ts_jest_1.createMock)();
    const contractServiceMock = (0, ts_jest_1.createMock)();
    const evmAddress = new EvmAddress_1.default(DataFixture_1.EvmAddressPropsFixture.create().value);
    const externalPauseEvmAddress = new EvmAddress_1.default(DataFixture_1.EvmAddressPropsFixture.create().value);
    const externalControlEvmAddress = new EvmAddress_1.default(DataFixture_1.EvmAddressPropsFixture.create().value);
    const externalKycEvmAddress = new EvmAddress_1.default(DataFixture_1.EvmAddressPropsFixture.create().value);
    const transactionId = DataFixture_1.TransactionIdFixture.create().id;
    const hederaId = DataFixture_1.HederaIdPropsFixture.create();
    const hederaIdZeroAddress = DataFixture_1.HederaIdZeroAddressFixture.create().address;
    const errorMsg = DataFixture_1.ErrorMsgFixture.create().msg;
    beforeEach(() => {
        handler = new CreateBondFixedRateCommandHandler_1.CreateBondFixedRateCommandHandler(accountServiceMock, transactionServiceMock, mirrorNodeAdapterMock, contractServiceMock);
        command = BondFixedRateFixture_1.CreateBondFixedRateCommandFixture.create();
    });
    afterEach(() => {
        jest.resetAllMocks();
    });
    describe("execute", () => {
        describe("error cases", () => {
            it("should throw InvalidRequest if factory is not provided", async () => {
                const commandWithNotFactory = {
                    ...command,
                    factory: undefined,
                };
                const resultPromise = handler.execute(commandWithNotFactory);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the bond fixed rate: Factory not found in request`),
                    errorCode: BaseError_1.ErrorCode.InvalidRequest,
                });
            });
            it("should throw InvalidRequest if resolver is not provided", async () => {
                const commandWithNotResolver = {
                    ...command,
                    resolver: undefined,
                };
                const resultPromise = handler.execute(commandWithNotResolver);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the bond fixed rate: Resolver not found in request`),
                    errorCode: BaseError_1.ErrorCode.InvalidRequest,
                });
            });
            it("should throw InvalidRequest if configId is not provided", async () => {
                const commandWithNotConfigId = {
                    ...command,
                    configId: undefined,
                };
                const resultPromise = handler.execute(commandWithNotConfigId);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the bond fixed rate: Config Id not found in request`),
                    errorCode: BaseError_1.ErrorCode.InvalidRequest,
                });
            });
            it("should throw InvalidRequest if configVersion is not provided", async () => {
                const commandWithNotConfigVersion = {
                    ...command,
                    configVersion: undefined,
                };
                const resultPromise = handler.execute(commandWithNotConfigVersion);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the bond fixed rate: Config Version not found in request`),
                    errorCode: BaseError_1.ErrorCode.InvalidRequest,
                });
            });
            it("throws CreateBondFixedRateCommandError when command fails with uncaught error", async () => {
                const fakeError = new Error(errorMsg);
                accountServiceMock.getAccountEvmAddress.mockRejectedValue(fakeError);
                const resultPromise = handler.execute(command);
                await expect(resultPromise).rejects.toBeInstanceOf(CreateBondFixedRateCommandError_1.CreateBondFixedRateCommandError);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the bond fixed rate: ${errorMsg}`),
                    errorCode: BaseError_1.ErrorCode.UncaughtCommandError,
                });
            });
        });
        describe("success cases", () => {
            it("should successfully create a bond with bondAddress in response", async () => {
                contractServiceMock.getContractEvmAddress
                    .mockResolvedValueOnce(evmAddress)
                    .mockResolvedValueOnce(evmAddress)
                    .mockResolvedValueOnce(evmAddress)
                    .mockResolvedValueOnce(evmAddress);
                contractServiceMock.getEvmAddressesFromHederaIds
                    .mockResolvedValueOnce([externalPauseEvmAddress])
                    .mockResolvedValueOnce([externalControlEvmAddress])
                    .mockResolvedValueOnce([externalKycEvmAddress]);
                accountServiceMock.getAccountEvmAddress.mockResolvedValue(evmAddress).mockResolvedValue(evmAddress);
                transactionServiceMock.getHandler().createBondFixedRate.mockResolvedValue({
                    id: transactionId,
                    response: { bondAddress: evmAddress.value },
                });
                mirrorNodeAdapterMock.getHederaIdfromContractAddress.mockResolvedValue(transactionId);
                transactionServiceMock.getTransactionResult.mockResolvedValue(evmAddress.value);
                const result = await handler.execute(command);
                expect(result).toBeInstanceOf(CreateBondFixedRateCommand_1.CreateBondFixedRateCommandResponse);
                expect(result.securityId.value).toBe(transactionId);
                expect(result.transactionId).toBe(transactionId);
                expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes(4);
                expect(contractServiceMock.getEvmAddressesFromHederaIds).toHaveBeenCalledTimes(3);
                expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(2);
                expect(transactionServiceMock.getHandler().createBondFixedRate).toHaveBeenCalledTimes(1);
                expect(transactionServiceMock.getTransactionResult).toHaveBeenCalledTimes(1);
                expect(mirrorNodeAdapterMock.getHederaIdfromContractAddress).toHaveBeenCalledTimes(1);
                expect(transactionServiceMock.getHandler().createBondFixedRate).toHaveBeenCalledWith(expect.objectContaining(command.security), expect.objectContaining({
                    currency: command.currency,
                    nominalValue: BigDecimal_1.default.fromString(command.nominalValue),
                    startingDate: parseInt(command.startingDate),
                    maturityDate: parseInt(command.maturityDate),
                }), evmAddress, evmAddress, command.configId, command.configVersion, evmAddress, evmAddress, [externalPauseEvmAddress], [externalControlEvmAddress], [externalKycEvmAddress], evmAddress, [evmAddress], command.proceedRecipientsData, command.factory?.toString());
                expect(transactionServiceMock.getTransactionResult).toHaveBeenCalledWith(expect.objectContaining({
                    res: {
                        id: transactionId,
                        response: { bondAddress: evmAddress.value },
                    },
                    result: evmAddress.value,
                    className: CreateBondFixedRateCommandHandler_1.CreateBondFixedRateCommandHandler.name,
                    position: 0,
                    numberOfResultsItems: 1,
                }));
            });
            it("should handle error and return fallback response if response code is 1", async () => {
                contractServiceMock.getContractEvmAddress.mockResolvedValue(evmAddress);
                mirrorNodeAdapterMock.getContractInfo.mockResolvedValue({
                    id: hederaId.value,
                    evmAddress: evmAddress.value,
                });
                transactionServiceMock.getHandler().createBondFixedRate.mockResolvedValue({
                    id: transactionId,
                    response: 1,
                });
                const result = await handler.execute(command);
                expect(result).toBeInstanceOf(CreateBondFixedRateCommand_1.CreateBondFixedRateCommandResponse);
                expect(result.securityId.toString()).toBe(hederaIdZeroAddress);
                expect(result.transactionId.toString()).toBe(transactionId);
            });
        });
    });
});
