"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 types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const modifyCaDefaults_1 = require("../modifyCaDefaults");
const utilsProcedureModule = __importStar(require("../utils"));
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('modifyCaDefaults procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let targetsToTargetIdentitiesStub;
    let percentageToPermillStub;
    let stringToIdentityIdStub;
    let assertCaTargetsValidStub;
    let assertCaTaxWithholdingsValidStub;
    let ticker;
    let rawTicker;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        targetsToTargetIdentitiesStub = sinon_1.default.stub(utilsConversionModule, 'targetsToTargetIdentities');
        percentageToPermillStub = sinon_1.default.stub(utilsConversionModule, 'percentageToPermill');
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
        ticker = 'someTicker';
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        assertCaTargetsValidStub = sinon_1.default.stub(utilsProcedureModule, 'assertCaTargetsValid');
        assertCaTaxWithholdingsValidStub = sinon_1.default.stub(utilsProcedureModule, 'assertCaTaxWithholdingsValid');
    });
    let addTransactionStub;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
    });
    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 user has not passed any arguments', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {})).rejects.toThrow('Nothing to modify');
    });
    test('should throw an error if the new targets are the same as the current ones', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const targets = {
            identities: [],
            treatment: types_2.TargetTreatment.Exclude,
        };
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: { corporateActionsGetDefaults: { targets } },
        });
        return expect(modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            targets,
        })).rejects.toThrow('New targets are the same as the current ones');
    });
    test('should throw an error if the new default tax withholding is the same as the current one', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const defaultTaxWithholding = new bignumber_js_1.default(10);
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: { corporateActionsGetDefaults: { defaultTaxWithholding } },
        });
        return expect(modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            defaultTaxWithholding,
        })).rejects.toThrow('New default tax withholding is the same as the current one');
    });
    test('should throw an error if the new tax withholdings are the same as the current ones', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const taxWithholdings = [
            {
                identity: mocks_1.entityMockUtils.getIdentityInstance({ did: 'someDid' }),
                percentage: new bignumber_js_1.default(15),
            },
        ];
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: { corporateActionsGetDefaults: { taxWithholdings } },
        });
        return expect(modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            taxWithholdings,
        })).rejects.toThrow('New per-Identity tax withholding percentages are the same as current ones');
    });
    test('should add a set default targets transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('corporateAction', 'setDefaultTargets');
        let targets = {
            identities: [],
            treatment: types_2.TargetTreatment.Exclude,
        };
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: {
                corporateActionsGetDefaults: {
                    targets: {
                        identities: [mocks_1.entityMockUtils.getIdentityInstance({ did: 'someDid' })],
                        treatment: types_2.TargetTreatment.Include,
                    },
                },
            },
        });
        let rawTargets = mocks_1.dsMockUtils.createMockTargetIdentities({
            identities: [],
            treatment: 'Exclude',
        });
        targetsToTargetIdentitiesStub.withArgs(targets, mockContext).returns(rawTargets);
        yield modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            targets,
        });
        sinon_1.default.assert.calledWith(assertCaTargetsValidStub, targets, mockContext);
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({}), rawTicker, rawTargets);
        rawTargets = mocks_1.dsMockUtils.createMockTargetIdentities({
            identities: ['someDid', 'otherDid'],
            treatment: 'Exclude',
        });
        targets = {
            identities: ['someDid', 'otherDid'],
            treatment: types_2.TargetTreatment.Exclude,
        };
        targetsToTargetIdentitiesStub.withArgs(targets, mockContext).returns(rawTargets);
        yield modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            targets,
        });
        sinon_1.default.assert.calledWith(assertCaTargetsValidStub, targets, mockContext);
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({}), rawTicker, rawTargets);
    }));
    test('should add a set default withholding tax transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('corporateAction', 'setDefaultWithholdingTax');
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: {
                corporateActionsGetDefaults: {
                    defaultTaxWithholding: new bignumber_js_1.default(10),
                },
            },
        });
        const rawPercentage = mocks_1.dsMockUtils.createMockPermill(150000);
        percentageToPermillStub.withArgs(new bignumber_js_1.default(15), mockContext).returns(rawPercentage);
        yield modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            defaultTaxWithholding: new bignumber_js_1.default(15),
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({}), rawTicker, rawPercentage);
    }));
    test('should add a batch of set did withholding tax transactions to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('corporateAction', 'setDidWithholdingTax');
        mocks_1.entityMockUtils.configureMocks({
            securityTokenOptions: {
                corporateActionsGetDefaults: {
                    taxWithholdings: [],
                },
            },
        });
        const rawDid = mocks_1.dsMockUtils.createMockIdentityId('someDid');
        const rawPercentage = mocks_1.dsMockUtils.createMockPermill(250000);
        stringToIdentityIdStub.withArgs('someDid', mockContext).returns(rawDid);
        percentageToPermillStub.withArgs(new bignumber_js_1.default(25), mockContext).returns(rawPercentage);
        const taxWithholdings = [
            {
                identity: 'someDid',
                percentage: new bignumber_js_1.default(25),
            },
        ];
        yield modifyCaDefaults_1.prepareModifyCaDefaults.call(proc, {
            ticker,
            taxWithholdings,
        });
        sinon_1.default.assert.calledWith(assertCaTaxWithholdingsValidStub, taxWithholdings, mockContext);
        sinon_1.default.assert.calledWith(mocks_1.procedureMockUtils.getAddBatchTransactionStub(), transaction, sinon_1.default.match({}), [[rawTicker, rawDid, rawPercentage]]);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = modifyCaDefaults_1.getAuthorization.bind(proc);
            const args = {
                ticker,
            };
            expect(boundFunc(args)).toEqual({
                permissions: {
                    transactions: [],
                    portfolios: [],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                },
            });
            expect(boundFunc(Object.assign(Object.assign({}, args), { targets: { identities: [], treatment: types_2.TargetTreatment.Include }, defaultTaxWithholding: new bignumber_js_1.default(10), taxWithholdings: [] }))).toEqual({
                permissions: {
                    transactions: [
                        types_1.TxTags.corporateAction.SetDefaultTargets,
                        types_1.TxTags.corporateAction.SetDefaultWithholdingTax,
                        types_1.TxTags.corporateAction.SetDidWithholdingTax,
                    ],
                    portfolios: [],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                },
            });
        });
    });
});
//# sourceMappingURL=modifyCaDefaults.js.map