"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 payDividends_1 = require("../payDividends");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
describe('payDividends procedure', () => {
    const ticker = 'SOME_TICKER';
    const did = 'someDid';
    const id = new bignumber_js_1.default(1);
    const paymentDate = new Date('10/14/1987');
    const expiryDate = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365);
    // eslint-disable-next-line @typescript-eslint/naming-convention
    const rawCaId = mocks_1.dsMockUtils.createMockCAId({ ticker, local_id: id });
    let distribution;
    let mockContext;
    let stringToIdentityIdStub;
    let addBatchTransactionStub;
    let payDividendsTransaction;
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks({
            dividendDistributionOptions: {
                ticker,
                id,
                paymentDate,
                expiryDate,
            },
        });
        mocks_1.dsMockUtils.initMocks({ contextOptions: { did } });
        mocks_1.procedureMockUtils.initMocks();
        sinon_1.default.stub(utilsConversionModule, 'corporateActionIdentifierToCaId').returns(rawCaId);
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
    });
    beforeEach(() => {
        addBatchTransactionStub = mocks_1.procedureMockUtils.getAddBatchTransactionStub();
        payDividendsTransaction = mocks_1.dsMockUtils.createTxStub('capitalDistribution', 'pushBenefit');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should add a stop Offering transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const targets = ['someDid'];
        const identityId = mocks_1.dsMockUtils.createMockIdentityId(targets[0]);
        mocks_1.dsMockUtils.createQueryStub('capitalDistribution', 'holderPaid', {
            multi: [mocks_1.dsMockUtils.createMockBool(false)],
        });
        distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
            targets: {
                identities: targets.map(identityDid => mocks_1.entityMockUtils.getIdentityInstance({ did: identityDid })),
                treatment: types_1.TargetTreatment.Include,
            },
            ticker,
            id,
            paymentDate,
            expiryDate,
        });
        stringToIdentityIdStub.returns(identityId);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        yield payDividends_1.preparePayDividends.call(proc, { targets, distribution });
        sinon_1.default.assert.calledWith(addBatchTransactionStub, {
            transactions: [{ transaction: payDividendsTransaction, args: [rawCaId, identityId] }],
        });
    }));
    test('should throw an error if the Distribution is expired', () => __awaiter(void 0, void 0, void 0, function* () {
        const targets = ['someDid'];
        const date = new Date(new Date().getTime() + 1000 * 60 * 60);
        distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
            paymentDate: date,
            expiryDate,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        try {
            yield payDividends_1.preparePayDividends.call(proc, { targets, distribution });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe("The Distribution's payment date hasn't been reached");
        expect(err.data).toEqual({
            paymentDate: date,
        });
    }));
    test('should throw an error if the Distribution is expired', () => __awaiter(void 0, void 0, void 0, function* () {
        const targets = ['someDid'];
        const date = new Date(new Date().getTime() - 1000);
        distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
            expiryDate: date,
            paymentDate,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        try {
            yield payDividends_1.preparePayDividends.call(proc, { targets, distribution });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('The Distribution has already expired');
        expect(err.data).toEqual({
            expiryDate: date,
        });
    }));
    test('should throw an error if some of the supplied targets are not included in the Distribution', () => __awaiter(void 0, void 0, void 0, function* () {
        const excludedDid = 'someDid';
        mocks_1.dsMockUtils.createQueryStub('capitalDistribution', 'holderPaid', {
            multi: [mocks_1.dsMockUtils.createMockBool(true)],
        });
        distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
            targets: {
                identities: [mocks_1.entityMockUtils.getIdentityInstance({ did: 'otherDid' })],
                treatment: types_1.TargetTreatment.Include,
            },
            paymentDate,
            expiryDate,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        try {
            yield payDividends_1.preparePayDividends.call(proc, { targets: [excludedDid], distribution });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Some of the supplied Identities are not included in this Distribution');
        expect(err.data.excluded[0].did).toBe(excludedDid);
    }));
    test('should throw an error if some of the supplied targets has already claimed their benefits', () => __awaiter(void 0, void 0, void 0, function* () {
        const dids = ['someDid', 'otherDid'];
        const targets = [dids[0], mocks_1.entityMockUtils.getIdentityInstance({ did: dids[1] })];
        mocks_1.dsMockUtils.createQueryStub('capitalDistribution', 'holderPaid', {
            multi: [mocks_1.dsMockUtils.createMockBool(true)],
        });
        dids.forEach(targetDid => stringToIdentityIdStub
            .withArgs(targetDid)
            .returns(mocks_1.dsMockUtils.createMockIdentityId(targetDid)));
        distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
            targets: {
                identities: dids.map(identityDid => mocks_1.entityMockUtils.getIdentityInstance({ did: identityDid })),
                treatment: types_1.TargetTreatment.Include,
            },
            expiryDate,
            paymentDate,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let err;
        try {
            yield payDividends_1.preparePayDividends.call(proc, { targets, distribution });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Some of the supplied Identities have already either been paid or claimed their share of the Distribution');
        expect(err.data.targets[0].did).toEqual(dids[0]);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = payDividends_1.getAuthorization.bind(proc);
            distribution = mocks_1.entityMockUtils.getDividendDistributionInstance({
                ticker,
            });
            const result = yield boundFunc();
            expect(result).toEqual({
                permissions: {
                    assets: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.capitalDistribution.PushBenefit],
                },
            });
        }));
    });
});
//# sourceMappingURL=payDividends.js.map