"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 ts_jest_1 = require("@golevelup/ts-jest");
const CreateEquityCommandHandler_1 = require("./CreateEquityCommandHandler");
const CreateEquityCommand_1 = require("./CreateEquityCommand");
const EvmAddress_1 = __importDefault(require("../../../../../domain/context/contract/EvmAddress"));
const DataFixture_1 = require("../../../../../../__tests__/fixtures/shared/DataFixture");
const BigDecimal_1 = __importDefault(require("../../../../../domain/context/shared/BigDecimal"));
const EquityFixture_1 = require("../../../../../../__tests__/fixtures/equity/EquityFixture");
const BaseError_1 = require("../../../../../core/error/BaseError");
const CreateEquityCommandError_1 = require("./error/CreateEquityCommandError");
describe("CreateEquityCommandHandler", () => {
    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().value;
    const hederaIdZeroAddress = DataFixture_1.HederaIdZeroAddressFixture.create().address;
    const errorMsg = DataFixture_1.ErrorMsgFixture.create().msg;
    beforeEach(() => {
        handler = new CreateEquityCommandHandler_1.CreateEquityCommandHandler(transactionServiceMock, mirrorNodeAdapterMock, contractServiceMock, accountServiceMock);
        command = EquityFixture_1.CreateEquityCommandFixture.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 equity: 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 equity: 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 equity: 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 equity: Config Version not found in request`),
                    errorCode: BaseError_1.ErrorCode.InvalidRequest,
                });
            });
            it("throws CreateEquityCommandError when command fails with uncaught error", async () => {
                const fakeError = new Error(errorMsg);
                contractServiceMock.getContractEvmAddress.mockRejectedValue(fakeError);
                const resultPromise = handler.execute(command);
                await expect(resultPromise).rejects.toBeInstanceOf(CreateEquityCommandError_1.CreateEquityCommandError);
                await expect(resultPromise).rejects.toMatchObject({
                    message: expect.stringContaining(`An error occurred while creating the equity: ${errorMsg}`),
                    errorCode: BaseError_1.ErrorCode.UncaughtCommandError,
                });
            });
        });
        describe("success cases", () => {
            it("should successfully create an equity with equityAddress 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);
                transactionServiceMock.getHandler().createEquity.mockResolvedValue({
                    id: transactionId,
                    response: { equityAddress: evmAddress.value },
                });
                mirrorNodeAdapterMock.getHederaIdfromContractAddress.mockResolvedValue(hederaId);
                transactionServiceMock.getTransactionResult.mockResolvedValue(evmAddress.value);
                const result = await handler.execute(command);
                expect(result).toBeInstanceOf(CreateEquityCommand_1.CreateEquityCommandResponse);
                expect(result.securityId.value).toBe(hederaId);
                expect(result.transactionId).toBe(transactionId);
                expect(contractServiceMock.getContractEvmAddress).toHaveBeenCalledTimes(4);
                expect(contractServiceMock.getEvmAddressesFromHederaIds).toHaveBeenCalledTimes(3);
                expect(accountServiceMock.getAccountEvmAddress).toHaveBeenCalledTimes(1);
                expect(transactionServiceMock.getHandler().createEquity).toHaveBeenCalledTimes(1);
                expect(transactionServiceMock.getTransactionResult).toHaveBeenCalledTimes(1);
                expect(mirrorNodeAdapterMock.getHederaIdfromContractAddress).toHaveBeenCalledTimes(1);
                expect(transactionServiceMock.getHandler().createEquity).toHaveBeenCalledWith(expect.objectContaining(command.security), expect.objectContaining({
                    votingRight: command.votingRight,
                    informationRight: command.informationRight,
                    liquidationRight: command.liquidationRight,
                    subscriptionRight: command.subscriptionRight,
                    conversionRight: command.conversionRight,
                    redemptionRight: command.redemptionRight,
                    putRight: command.putRight,
                    dividendRight: command.dividendRight,
                    currency: command.currency,
                    nominalValue: BigDecimal_1.default.fromString(command.nominalValue),
                }), evmAddress, evmAddress, command.configId, command.configVersion, evmAddress, evmAddress, [externalPauseEvmAddress], [externalControlEvmAddress], [externalKycEvmAddress], evmAddress, command.factory?.toString());
                expect(transactionServiceMock.getTransactionResult).toHaveBeenCalledWith(expect.objectContaining({
                    res: {
                        id: transactionId,
                        response: { equityAddress: evmAddress.value },
                    },
                    result: evmAddress.value,
                    className: CreateEquityCommandHandler_1.CreateEquityCommandHandler.name,
                    position: 0,
                    numberOfResultsItems: 1,
                }));
            });
            it("should handle error and return fallback response if response code is 1", async () => {
                mirrorNodeAdapterMock.getContractInfo.mockResolvedValue({
                    id: hederaId,
                    evmAddress: evmAddress.value,
                });
                transactionServiceMock.getHandler().createEquity.mockResolvedValue({
                    id: transactionId,
                    response: 1,
                });
                const result = await handler.execute(command);
                expect(result).toBeInstanceOf(CreateEquityCommand_1.CreateEquityCommandResponse);
                expect(result.securityId.toString()).toBe(hederaIdZeroAddress);
                expect(result.transactionId.toString()).toBe(transactionId);
            });
        });
    });
});
