"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 setPermissionGroup_1 = require("../setPermissionGroup");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('setPermissionGroup procedure', () => {
    const ticker = 'SOME_TICKER';
    const did = 'someDid';
    const rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
    const rawIdentityId = mocks_1.dsMockUtils.createMockIdentityId(did);
    const rawExtrinsicPermissions = mocks_1.dsMockUtils.createMockExtrinsicPermissions({
        These: [
            /* eslint-disable @typescript-eslint/naming-convention */
            mocks_1.dsMockUtils.createMockPalletPermissions({
                pallet_name: mocks_1.dsMockUtils.createMockPalletName('Sto'),
                dispatchable_names: mocks_1.dsMockUtils.createMockDispatchableNames({
                    These: [mocks_1.dsMockUtils.createMockDispatchableName('invest')],
                }),
            }),
            /* eslint-enable @typescript-eslint/naming-convention */
        ],
    });
    let mockContext;
    let addTransactionStub;
    let externalAgentsChangeGroupTransaction;
    let permissionGroupIdentifierToAgentGroupStub;
    let stringToTickerStub;
    let stringToIdentityIdStub;
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks();
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        sinon_1.default
            .stub(utilsConversionModule, 'transactionPermissionsToExtrinsicPermissions')
            .returns(rawExtrinsicPermissions);
        permissionGroupIdentifierToAgentGroupStub = sinon_1.default.stub(utilsConversionModule, 'permissionGroupIdentifierToAgentGroup');
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        externalAgentsChangeGroupTransaction = mocks_1.dsMockUtils.createTxStub('externalAgents', 'changeGroup');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.returns(rawTicker);
        stringToIdentityIdStub.returns(rawIdentityId);
    });
    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 target is the last agent with full permissions', () => __awaiter(void 0, void 0, void 0, function* () {
        const group = mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
            ticker,
            type: types_1.PermissionGroupType.Full,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetAgents: [
                    {
                        agent: mocks_1.entityMockUtils.getIdentityInstance(),
                        group,
                    },
                ],
            }),
        });
        let error;
        try {
            yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
                identity: mocks_1.entityMockUtils.getIdentityInstance({
                    tokenPermissionsGetGroup: group,
                }),
                group: {
                    token: ticker,
                    transactions: {
                        type: types_1.PermissionType.Include,
                        values: [],
                    },
                },
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The target is the last Agent with full permissions for this Security Token. There should always be at least one Agent with full permissions');
    }));
    test('should throw an error if the target is not an agent', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetAgents: [],
            }),
        });
        let error;
        try {
            yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
                identity: mocks_1.entityMockUtils.getIdentityInstance(),
                group: {
                    token: ticker,
                    transactions: {
                        type: types_1.PermissionType.Include,
                        values: [],
                    },
                },
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The target must already be an Agent for the Security Token');
    }));
    test('should throw an error if the Agent is already part of the permission group', () => __awaiter(void 0, void 0, void 0, function* () {
        const identity = mocks_1.entityMockUtils.getIdentityInstance({
            tokenPermissionsGetGroup: mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
                ticker,
                type: types_1.PermissionGroupType.PolymeshV1Caa,
            }),
        });
        let group = mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
            ticker,
            type: types_1.PermissionGroupType.PolymeshV1Caa,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetAgents: [
                    {
                        agent: identity,
                        group,
                    },
                ],
            }),
        });
        let error;
        try {
            yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
                identity,
                token: ticker,
                group,
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The Agent is already part of this permission group');
        const id = new bignumber_js_1.default(1);
        group = mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
            ticker,
            id,
        });
        try {
            yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
                identity: mocks_1.entityMockUtils.getIdentityInstance({
                    tokenPermissionsGetGroup: group,
                }),
                token: ticker,
                group,
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The Agent is already part of this permission group');
    }));
    test('should add a change group transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const id = new bignumber_js_1.default(1);
        const identity = mocks_1.entityMockUtils.getIdentityInstance({
            tokenPermissionsGetGroup: mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
                ticker,
                type: types_1.PermissionGroupType.Full,
            }),
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetAgents: [
                    {
                        agent: identity,
                        group: mocks_1.entityMockUtils.getCustomPermissionGroupInstance(),
                    },
                ],
            }),
        });
        const rawAgentGroup = mocks_1.dsMockUtils.createMockAgentGroup({
            Custom: mocks_1.dsMockUtils.createMockU32(id.toNumber()),
        });
        permissionGroupIdentifierToAgentGroupStub
            .withArgs({ custom: id }, mockContext)
            .returns(rawAgentGroup);
        mocks_1.procedureMockUtils.getAddProcedureStub().resolves({
            transform: sinon_1.default
                .stub()
                .callsFake(cb => cb(mocks_1.entityMockUtils.getCustomPermissionGroupInstance({ ticker, id }))),
        });
        yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
            identity,
            group: {
                token: ticker,
                transactions: {
                    type: types_1.PermissionType.Include,
                    values: [],
                },
            },
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsChangeGroupTransaction, {}, rawTicker, rawIdentityId, rawAgentGroup);
        yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
            identity: mocks_1.entityMockUtils.getIdentityInstance({
                tokenPermissionsGetGroup: mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
                    ticker,
                    id,
                }),
            }),
            group: {
                token: ticker,
                transactions: {
                    type: types_1.PermissionType.Include,
                    values: [],
                },
            },
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsChangeGroupTransaction, {}, rawTicker, rawIdentityId, rawAgentGroup);
        yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
            identity: mocks_1.entityMockUtils.getIdentityInstance({
                tokenPermissionsGetGroup: mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
                    ticker,
                    type: types_1.PermissionGroupType.PolymeshV1Caa,
                }),
            }),
            token: ticker,
            group: mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
                ticker,
                type: types_1.PermissionGroupType.PolymeshV1Pia,
                isEqual: false,
            }),
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsChangeGroupTransaction, {}, rawTicker, rawIdentityId, rawAgentGroup);
        const fakeCustomPermissionGroup = mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
            ticker,
            id: new bignumber_js_1.default(2),
        });
        const result = yield setPermissionGroup_1.prepareSetPermissionGroup.call(proc, {
            identity: mocks_1.entityMockUtils.getIdentityInstance({
                tokenPermissionsGetGroup: mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
                    ticker,
                    id,
                    isEqual: false,
                }),
            }),
            token: ticker,
            group: fakeCustomPermissionGroup,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsChangeGroupTransaction, {}, rawTicker, rawIdentityId, rawAgentGroup);
        expect(result).toEqual(fakeCustomPermissionGroup);
    }));
    describe('prepareStorage', () => {
        test('should return the security token', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = setPermissionGroup_1.prepareStorage.bind(proc);
            let result = boundFunc({
                identity: mocks_1.entityMockUtils.getIdentityInstance(),
                group: { transactionGroups: [], token: ticker },
            });
            expect(result).toEqual({
                token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }),
            });
            result = boundFunc({
                identity: mocks_1.entityMockUtils.getIdentityInstance(),
                group: mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
                    ticker,
                }),
            });
            expect(result).toEqual({
                token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }),
            });
        });
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                    ticker,
                }),
            });
            const boundFunc = setPermissionGroup_1.getAuthorization.bind(proc);
            expect(boundFunc()).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.externalAgents.ChangeGroup],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=setPermissionGroup.js.map