"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const sinon_1 = __importDefault(require("sinon"));
const initiateCorporateAction_1 = require("../initiateCorporateAction");
const utilsProcedureModule = __importStar(require("../utils"));
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utils_1 = require("../../../types/utils");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('initiateCorporateAction procedure', () => {
    let ticker;
    let kind;
    let declarationDate;
    let checkpoint;
    let description;
    let targets;
    let defaultTaxWithholding;
    let taxWithholdings;
    let rawTicker;
    let rawKind;
    let rawDeclDate;
    let rawRecordDate;
    let rawDetails;
    let rawTargets;
    let rawTax;
    let rawWithholdings;
    let rawCaId;
    let mockContext;
    let addTransactionStub;
    let initiateCorporateActionTransaction;
    let maxDetailsLengthQueryStub;
    let stringToTickerStub;
    let corporateActionKindToCaKindStub;
    let dateToMomentStub;
    let checkpointToRecordDateSpecStub;
    let stringToTextStub;
    let targetsToTargetIdentitiesStub;
    let percentageToPermillStub;
    let stringToIdentityIdStub;
    let assertCaTargetsValidStub;
    let assertCaTaxWithholdingsValidStub;
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks();
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        ticker = 'SOME_TICKER';
        kind = types_1.CorporateActionKind.UnpredictableBenefit;
        declarationDate = new Date('10/14/1987');
        checkpoint = new Date(new Date().getTime() + 60 * 60 * 24 * 365);
        description = 'someDescription';
        targets = {
            identities: ['someDid'],
            treatment: types_1.TargetTreatment.Exclude,
        };
        defaultTaxWithholding = new bignumber_js_1.default(10);
        taxWithholdings = [{ identity: 'someDid', percentage: new bignumber_js_1.default(30) }];
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawKind = mocks_1.dsMockUtils.createMockCAKind(kind);
        rawDeclDate = mocks_1.dsMockUtils.createMockMoment(declarationDate.getTime());
        rawRecordDate = mocks_1.dsMockUtils.createMockRecordDateSpec({
            Scheduled: mocks_1.dsMockUtils.createMockMoment(checkpoint.getTime()),
        });
        rawDetails = mocks_1.dsMockUtils.createMockText(description);
        rawTargets = mocks_1.dsMockUtils.createMockTargetIdentities({
            identities: targets.identities,
            treatment: targets.treatment,
        });
        rawTax = mocks_1.dsMockUtils.createMockPermill(defaultTaxWithholding.toNumber());
        rawWithholdings = [
            utils_1.tuple(mocks_1.dsMockUtils.createMockIdentityId('someDid'), mocks_1.dsMockUtils.createMockPermill(30)),
        ];
        rawCaId = 'caId';
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        corporateActionKindToCaKindStub = sinon_1.default.stub(utilsConversionModule, 'corporateActionKindToCaKind');
        dateToMomentStub = sinon_1.default.stub(utilsConversionModule, 'dateToMoment');
        checkpointToRecordDateSpecStub = sinon_1.default.stub(utilsConversionModule, 'checkpointToRecordDateSpec');
        stringToTextStub = sinon_1.default.stub(utilsConversionModule, 'stringToText');
        targetsToTargetIdentitiesStub = sinon_1.default.stub(utilsConversionModule, 'targetsToTargetIdentities');
        percentageToPermillStub = sinon_1.default.stub(utilsConversionModule, 'percentageToPermill');
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
        assertCaTargetsValidStub = sinon_1.default.stub(utilsProcedureModule, 'assertCaTargetsValid');
        assertCaTaxWithholdingsValidStub = sinon_1.default.stub(utilsProcedureModule, 'assertCaTaxWithholdingsValid');
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub().returns([rawCaId]);
        initiateCorporateActionTransaction = mocks_1.dsMockUtils.createTxStub('corporateAction', 'initiateCorporateAction');
        maxDetailsLengthQueryStub = mocks_1.dsMockUtils.createQueryStub('corporateAction', 'maxDetailsLength', {
            returnValue: mocks_1.dsMockUtils.createMockU32(100),
        });
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        corporateActionKindToCaKindStub.withArgs(kind, mockContext).returns(rawKind);
        dateToMomentStub.withArgs(declarationDate, mockContext).returns(rawDeclDate);
        checkpointToRecordDateSpecStub.withArgs(checkpoint, mockContext).returns(rawRecordDate);
        stringToTextStub.withArgs(description, mockContext).returns(rawDetails);
        targetsToTargetIdentitiesStub.withArgs(targets, mockContext).returns(rawTargets);
        percentageToPermillStub.withArgs(defaultTaxWithholding, mockContext).returns(rawTax);
        percentageToPermillStub
            .withArgs(taxWithholdings[0].percentage, mockContext)
            .returns(rawWithholdings[0][1]);
        stringToIdentityIdStub.withArgs('someDid', mockContext).returns(rawWithholdings[0][0]);
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the declaration date is in the future', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        try {
            yield initiateCorporateAction_1.prepareInitiateCorporateAction.call(proc, {
                ticker,
                kind,
                declarationDate: new Date(new Date().getTime() + 1000 * 60 * 60),
                checkpoint,
                description,
                targets,
                defaultTaxWithholding,
                taxWithholdings,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Declaration date must be in the past');
    }));
    test('should throw an error if the description is too long', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        maxDetailsLengthQueryStub.returns(mocks_1.dsMockUtils.createMockU32(1));
        let err;
        try {
            yield initiateCorporateAction_1.prepareInitiateCorporateAction.call(proc, {
                ticker,
                kind,
                description,
                taxWithholdings,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Description too long');
        expect(err.data).toEqual({
            maxLength: 1,
        });
    }));
    test('should add a initiate corporate action transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield initiateCorporateAction_1.prepareInitiateCorporateAction.call(proc, {
            ticker,
            kind,
            declarationDate,
            checkpoint,
            description,
            targets,
            defaultTaxWithholding,
            taxWithholdings,
        });
        sinon_1.default.assert.calledWith(assertCaTargetsValidStub, targets, mockContext);
        sinon_1.default.assert.calledWith(assertCaTaxWithholdingsValidStub, taxWithholdings, mockContext);
        sinon_1.default.assert.calledWith(addTransactionStub, initiateCorporateActionTransaction, sinon_1.default.match({
            resolvers: sinon_1.default.match.array,
        }), rawTicker, rawKind, rawDeclDate, rawRecordDate, rawDetails, rawTargets, rawTax, rawWithholdings);
        expect(result).toEqual(rawCaId);
        yield initiateCorporateAction_1.prepareInitiateCorporateAction.call(proc, {
            ticker,
            kind,
            declarationDate,
            description,
            targets,
            defaultTaxWithholding,
            taxWithholdings,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, initiateCorporateActionTransaction, sinon_1.default.match({
            resolvers: sinon_1.default.match.array,
        }), rawTicker, rawKind, rawDeclDate, null, rawDetails, rawTargets, rawTax, rawWithholdings);
        yield initiateCorporateAction_1.prepareInitiateCorporateAction.call(proc, {
            ticker,
            kind,
            declarationDate,
            description,
            targets,
            defaultTaxWithholding,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, initiateCorporateActionTransaction, sinon_1.default.match({
            resolvers: sinon_1.default.match.array,
        }), rawTicker, rawKind, rawDeclDate, null, rawDetails, rawTargets, rawTax, null);
    }));
    describe('caIdResolver', () => {
        const filterEventRecordsStub = sinon_1.default.stub(utilsInternalModule, 'filterEventRecords');
        const id = 'caId';
        beforeEach(() => {
            filterEventRecordsStub.returns([mocks_1.dsMockUtils.createMockIEvent(['data', id])]);
        });
        afterEach(() => {
            filterEventRecordsStub.reset();
        });
        test('should return the CAId ', () => {
            const result = initiateCorporateAction_1.createCaIdResolver()({});
            expect(result).toBe(id);
        });
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = initiateCorporateAction_1.getAuthorization.bind(proc);
            const args = {
                ticker,
            };
            expect(boundFunc(args)).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.corporateAction.InitiateCorporateAction],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=initiateCorporateAction.js.map