"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 createGroup_1 = require("../createGroup");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/Sto', require("../../../testUtils/mocks/entities").mockStoModule('~/api/entities/Sto'));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('createGroup procedure', () => {
    const ticker = 'SOMETICKER';
    const transactions = {
        type: types_1.PermissionType.Include,
        values: [types_1.TxTags.sto.Invest, types_1.TxTags.asset.CreateAsset],
    };
    const rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
    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 externalAgentsCreateGroupTransaction;
    let permissionsLikeToPermissionsStub;
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks();
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        sinon_1.default.stub(utilsConversionModule, 'stringToTicker').returns(rawTicker);
        sinon_1.default
            .stub(utilsConversionModule, 'transactionPermissionsToExtrinsicPermissions')
            .returns(rawExtrinsicPermissions);
        permissionsLikeToPermissionsStub = sinon_1.default.stub(utilsConversionModule, 'permissionsLikeToPermissions');
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        externalAgentsCreateGroupTransaction = mocks_1.dsMockUtils.createTxStub('externalAgents', 'createGroup');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
    });
    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();
    });
    describe('createCreateGroupResolver', () => {
        const agId = new bignumber_js_1.default(1);
        const rawAgId = mocks_1.dsMockUtils.createMockU64(agId.toNumber());
        sinon_1.default
            .stub(utilsInternalModule, 'filterEventRecords')
            .returns([mocks_1.dsMockUtils.createMockIEvent(['someDid', rawTicker, rawAgId])]);
        test('should return the new CustomPermissionGroup', () => {
            const result = createGroup_1.createCreateGroupResolver(mockContext)({});
            expect(result.id).toEqual(agId);
            expect(result.token.ticker).toEqual(ticker);
        });
    });
    test('should throw an error if there already exists a group with exactly the same permissions', () => __awaiter(void 0, void 0, void 0, function* () {
        const customId = new bignumber_js_1.default(1);
        let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetGroups: {
                    custom: [
                        mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
                            ticker,
                            id: customId,
                            getPermissions: {
                                transactions,
                                transactionGroups: [],
                            },
                        }),
                    ],
                    known: [],
                },
            }),
        });
        permissionsLikeToPermissionsStub.returns({ transactions });
        let error;
        try {
            yield createGroup_1.prepareCreateGroup.call(proc, {
                ticker,
                permissions: { transactions },
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('There already exists a group with the exact same permissions');
        expect(error.data.groupId).toEqual(customId);
        proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetGroups: {
                    custom: [],
                    known: [
                        mocks_1.entityMockUtils.getKnownPermissionGroupInstance({
                            ticker,
                            type: types_1.PermissionGroupType.Full,
                            getPermissions: {
                                transactions: null,
                                transactionGroups: [],
                            },
                        }),
                    ],
                },
            }),
        });
        permissionsLikeToPermissionsStub.returns({
            tokens: null,
            portfolios: null,
            transactionGroups: [],
            transactions: null,
        });
        try {
            yield createGroup_1.prepareCreateGroup.call(proc, {
                ticker,
                permissions: {
                    transactions: {
                        type: types_1.PermissionType.Include,
                        values: [],
                    },
                },
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('There already exists a group with the exact same permissions');
        expect(error.data.groupId).toEqual(types_1.PermissionGroupType.Full);
    }));
    test('should add a create group transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({
                ticker,
                permissionsGetGroups: {
                    custom: [
                        mocks_1.entityMockUtils.getCustomPermissionGroupInstance({
                            ticker,
                            id: new bignumber_js_1.default(2),
                            getPermissions: {
                                transactions: null,
                                transactionGroups: [],
                            },
                        }),
                    ],
                    known: [],
                },
            }),
        });
        const fakePermissions = { transactions };
        permissionsLikeToPermissionsStub
            .withArgs(fakePermissions, mockContext)
            .returns({ transactions });
        yield createGroup_1.prepareCreateGroup.call(proc, {
            ticker,
            permissions: fakePermissions,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsCreateGroupTransaction, sinon_1.default.match({ resolvers: sinon_1.default.match.array }), rawTicker, rawExtrinsicPermissions);
        permissionsLikeToPermissionsStub
            .withArgs({
            transactions: {
                type: types_1.PermissionType.Include,
                values: [],
            },
        }, mockContext)
            .returns({ transactions: null });
        yield createGroup_1.prepareCreateGroup.call(proc, {
            ticker,
            permissions: { transactions },
        });
        sinon_1.default.assert.calledWith(addTransactionStub, externalAgentsCreateGroupTransaction, sinon_1.default.match({ resolvers: sinon_1.default.match.array }), rawTicker, rawExtrinsicPermissions);
    }));
    describe('prepareStorage', () => {
        test('should return the security token', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = createGroup_1.prepareStorage.bind(proc);
            const result = boundFunc({ 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 = createGroup_1.getAuthorization.bind(proc);
            expect(boundFunc()).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.externalAgents.CreateGroup],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=createGroup.js.map