"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 inviteAccount_1 = require("../inviteAccount");
const internal_1 = require("../../../internal");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Account', require("../../../testUtils/mocks/entities").mockAccountModule('~/api/entities/Account'));
describe('inviteAccount procedure', () => {
    let mockContext;
    let addTransactionStub;
    let authorizationToAuthorizationDataStub;
    let dateToMomentStub;
    let signerToStringStub;
    let signerValueToSignatoryStub;
    let permissionsLikeToPermissionsStub;
    let args;
    const authId = new bignumber_js_1.default(1);
    const address = 'targetAccount';
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        authorizationToAuthorizationDataStub = sinon_1.default.stub(utilsConversionModule, 'authorizationToAuthorizationData');
        dateToMomentStub = sinon_1.default.stub(utilsConversionModule, 'dateToMoment');
        signerToStringStub = sinon_1.default.stub(utilsConversionModule, 'signerToString');
        signerValueToSignatoryStub = sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        permissionsLikeToPermissionsStub = sinon_1.default.stub(utilsConversionModule, 'permissionsLikeToPermissions');
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        args = { targetAccount: address, identity: mocks_1.entityMockUtils.getIdentityInstance() };
    });
    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 add an add authorization transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const expiry = new Date('1/1/2040');
        const target = new internal_1.Account({ address }, mockContext);
        const signer = mocks_1.entityMockUtils.getAccountInstance({ address: 'someFakeAccount' });
        const rawSignatory = mocks_1.dsMockUtils.createMockSignatory({
            Account: mocks_1.dsMockUtils.createMockAccountId('someAccountId'),
        });
        const rawAuthorizationData = mocks_1.dsMockUtils.createMockAuthorizationData({
            JoinIdentity: mocks_1.dsMockUtils.createMockPermissions({
                asset: mocks_1.dsMockUtils.createMockAssetPermissions('Whole'),
                extrinsic: mocks_1.dsMockUtils.createMockExtrinsicPermissions('Whole'),
                portfolio: mocks_1.dsMockUtils.createMockPortfolioPermissions('Whole'),
            }),
        });
        const rawExpiry = mocks_1.dsMockUtils.createMockMoment(expiry.getTime());
        const sentAuthorizations = {
            data: [
                new internal_1.AuthorizationRequest({
                    target,
                    issuer: mocks_1.entityMockUtils.getIdentityInstance(),
                    authId,
                    expiry: null,
                    data: {
                        type: types_2.AuthorizationType.JoinIdentity,
                        value: {
                            tokens: null,
                            transactions: null,
                            transactionGroups: [],
                            portfolios: null,
                        },
                    },
                }, mockContext),
            ],
            next: 1,
            count: 1,
        };
        mocks_1.dsMockUtils.configureMocks({
            contextOptions: {
                sentAuthorizations,
                secondaryKeys: [
                    {
                        signer,
                        permissions: {
                            tokens: null,
                            portfolios: null,
                            transactions: null,
                            transactionGroups: [],
                        },
                    },
                ],
            },
        });
        mocks_1.entityMockUtils.getAccountGetIdentityStub().resolves(null);
        signerToStringStub.withArgs(signer).returns(signer.address);
        signerToStringStub.withArgs(args.targetAccount).returns(address);
        signerToStringStub.withArgs(target).returns('someValue');
        signerValueToSignatoryStub
            .withArgs({ type: types_2.SignerType.Account, value: address }, mockContext)
            .returns(rawSignatory);
        authorizationToAuthorizationDataStub.returns(rawAuthorizationData);
        dateToMomentStub.withArgs(expiry, mockContext).returns(rawExpiry);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('identity', 'addAuthorization');
        yield inviteAccount_1.prepareInviteAccount.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawSignatory, rawAuthorizationData, null);
        yield inviteAccount_1.prepareInviteAccount.call(proc, Object.assign(Object.assign({}, args), { expiry }));
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawSignatory, rawAuthorizationData, rawExpiry);
        permissionsLikeToPermissionsStub.resolves({
            tokens: null,
            transactions: null,
            portfolios: null,
        });
        yield inviteAccount_1.prepareInviteAccount.call(proc, Object.assign(Object.assign({}, args), { permissions: {
                tokens: null,
                transactions: null,
                portfolios: null,
            } }));
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawSignatory, rawAuthorizationData, null);
    }));
    test('should throw an error if the passed account is already part of an Identity', () => {
        const identity = mocks_1.entityMockUtils.getIdentityInstance();
        const targetAccount = mocks_1.entityMockUtils.getAccountInstance({
            address: 'someAddress',
            getIdentity: identity,
        });
        signerToStringStub.withArgs(args.targetAccount).returns(address);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(inviteAccount_1.prepareInviteAccount.call(proc, { targetAccount, identity })).rejects.toThrow('The target Account is already part of an Identity');
    });
    test('should throw an error if the passed account has a pending authorization to accept', () => {
        const target = mocks_1.entityMockUtils.getAccountInstance({
            address,
        });
        const signer = mocks_1.entityMockUtils.getAccountInstance({ address: 'someFakeAccount' });
        const sentAuthorizations = {
            data: [
                new internal_1.AuthorizationRequest({
                    target,
                    issuer: mocks_1.entityMockUtils.getIdentityInstance(),
                    authId,
                    expiry: null,
                    data: {
                        type: types_2.AuthorizationType.JoinIdentity,
                        value: {
                            tokens: null,
                            transactions: null,
                            transactionGroups: [],
                            portfolios: null,
                        },
                    },
                }, mockContext),
            ],
            next: 1,
            count: 1,
        };
        const identity = mocks_1.entityMockUtils.getIdentityInstance({
            authorizations: {
                getSent: sentAuthorizations,
            },
            getSecondaryKeys: [
                {
                    signer,
                    permissions: {
                        tokens: null,
                        portfolios: null,
                        transactions: null,
                        transactionGroups: [],
                    },
                },
            ],
        });
        mocks_1.entityMockUtils.getAccountGetIdentityStub().resolves(null);
        signerToStringStub.withArgs(signer).returns(signer.address);
        signerToStringStub.withArgs(args.targetAccount).returns(address);
        signerToStringStub.withArgs(target).returns(address);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(inviteAccount_1.prepareInviteAccount.call(proc, Object.assign(Object.assign({}, args), { identity }))).rejects.toThrow('The target Account already has a pending invitation to join this Identity');
    });
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = inviteAccount_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                roles: [{ type: types_2.RoleType.Identity, did: args.identity.did }],
                permissions: {
                    transactions: [types_1.TxTags.identity.AddAuthorization],
                    tokens: [],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=inviteAccount.js.map