"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 types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const inviteExternalAgent_1 = require("../inviteExternalAgent");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
jest.mock('~/api/entities/CustomPermissionGroup', require("../../../testUtils/mocks/entities").mockCustomPermissionGroupModule('~/api/entities/CustomPermissionGroup'));
jest.mock('~/api/entities/KnownPermissionGroup', require("../../../testUtils/mocks/entities").mockKnownPermissionGroupModule('~/api/entities/KnownPermissionGroup'));
describe('inviteExternalAgent procedure', () => {
    let mockContext;
    let authorizationToAuthorizationDataStub;
    let signerToStringStub;
    let signerValueToSignatoryStub;
    let ticker;
    let asset;
    let rawTicker;
    let rawAgentGroup;
    let target;
    let addTransactionStub;
    let rawSignatory;
    let rawAuthorizationData;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        authorizationToAuthorizationDataStub = sinon_1.default.stub(utilsConversionModule, 'authorizationToAuthorizationData');
        signerToStringStub = sinon_1.default.stub(utilsConversionModule, 'signerToString');
        signerValueToSignatoryStub = sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        ticker = 'someTicker';
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawAgentGroup = mocks_1.dsMockUtils.createMockAgentGroup('Full');
        asset = mocks_1.entityMockUtils.getAssetInstance({ ticker });
        target = 'someDid';
        rawSignatory = mocks_1.dsMockUtils.createMockSignatory({
            Identity: mocks_1.dsMockUtils.createMockIdentityId(target),
        });
        rawAuthorizationData = mocks_1.dsMockUtils.createMockAuthorizationData({
            BecomeAgent: [rawTicker, rawAgentGroup],
        });
    });
    beforeEach(() => {
        mocks_1.entityMockUtils.configureMocks({
            assetOptions: {
                corporateActionsGetAgents: [],
            },
        });
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        authorizationToAuthorizationDataStub.returns(rawAuthorizationData);
        signerToStringStub.returns(target);
        signerValueToSignatoryStub.returns(rawSignatory);
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
    });
    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('prepareStorage', () => {
        test('should return the Asset', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = inviteExternalAgent_1.prepareStorage.bind(proc);
            const result = boundFunc({
                ticker,
                target,
                permissions: mocks_1.entityMockUtils.getCustomPermissionGroupInstance(),
            });
            expect(result).toEqual({
                asset,
            });
        });
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                asset,
            });
            const boundFunc = inviteExternalAgent_1.getAuthorization.bind(proc);
            expect(boundFunc()).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.identity.AddAuthorization],
                    assets: [asset],
                    portfolios: [],
                },
            });
        });
    });
    test('should throw an error if the target identity is already an External Agent', () => {
        const args = {
            target,
            ticker,
            permissions: mocks_1.entityMockUtils.getKnownPermissionGroupInstance(),
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            asset: mocks_1.entityMockUtils.getAssetInstance({
                permissionsGetAgents: [
                    {
                        agent: mocks_1.entityMockUtils.getIdentityInstance({ did: target }),
                        group: mocks_1.entityMockUtils.getKnownPermissionGroupInstance(),
                    },
                ],
            }),
        });
        return expect(inviteExternalAgent_1.prepareInviteExternalAgent.call(proc, args)).rejects.toThrow('The target Identity is already an External Agent');
    });
    test('should add an add authorization transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const transaction = mocks_1.dsMockUtils.createTxStub('identity', 'addAuthorization');
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            asset: mocks_1.entityMockUtils.getAssetInstance({
                permissionsGetAgents: [
                    {
                        agent: { did: 'otherDid' },
                        group: mocks_1.entityMockUtils.getCustomPermissionGroupInstance(),
                    },
                ],
            }),
        });
        mocks_1.procedureMockUtils.getAddProcedureStub().resolves({
            transform: (cb) => {
                const res = cb();
                return Object.assign(Object.assign({}, res), { transform: (ocb) => ocb() });
            },
        });
        yield inviteExternalAgent_1.prepareInviteExternalAgent.call(proc, {
            target,
            ticker,
            permissions: mocks_1.entityMockUtils.getKnownPermissionGroupInstance(),
        });
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction,
            resolvers: sinon_1.default.match.array,
            args: [rawSignatory, rawAuthorizationData, null],
        }));
        yield inviteExternalAgent_1.prepareInviteExternalAgent.call(proc, {
            target: mocks_1.entityMockUtils.getIdentityInstance({ did: target }),
            ticker,
            permissions: {
                transactions: {
                    values: [],
                    type: types_2.PermissionType.Include,
                },
            },
        });
        sinon_1.default.assert.calledWith(addTransactionStub, sinon_1.default.match({
            transaction,
            resolvers: sinon_1.default.match.array,
            args: [rawSignatory, rawAuthorizationData, null],
        }));
    }));
});
//# sourceMappingURL=inviteExternalAgent.js.map