"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 consumeAddMultiSigSignerAuthorization_1 = require("../consumeAddMultiSigSignerAuthorization");
const internal_1 = require("../../../internal");
const mocks_1 = require("../../../testUtils/mocks");
const types_1 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
describe('consumeJoinSignerAuthorization procedure', () => {
    let mockContext;
    let targetAddress;
    let numberToU64Stub;
    let booleanToBoolStub;
    let rawTrue;
    let rawFalse;
    let authId;
    let rawAuthId;
    beforeAll(() => {
        targetAddress = 'someAddress';
        mocks_1.dsMockUtils.initMocks({
            contextOptions: {
                currentPairAddress: targetAddress,
            },
        });
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        numberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'numberToU64');
        booleanToBoolStub = sinon_1.default.stub(utilsConversionModule, 'booleanToBool');
        authId = new bignumber_js_1.default(1);
        rawAuthId = mocks_1.dsMockUtils.createMockU64(authId.toNumber());
        rawTrue = mocks_1.dsMockUtils.createMockBool(true);
        rawFalse = mocks_1.dsMockUtils.createMockBool(false);
        sinon_1.default.stub(utilsConversionModule, 'addressToKey');
    });
    let addTransactionStub;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        numberToU64Stub.withArgs(authId, mockContext).returns(rawAuthId);
        booleanToBoolStub.withArgs(true, mockContext).returns(rawTrue);
        booleanToBoolStub.withArgs(false, mockContext).returns(rawFalse);
    });
    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 Authorization Request is expired', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const target = mocks_1.entityMockUtils.getAccountInstance({ address: 'someAddress' });
        expect(consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
            authRequest: new internal_1.AuthorizationRequest({
                target,
                issuer: mocks_1.entityMockUtils.getIdentityInstance(),
                authId,
                expiry: new Date('10/14/1987'),
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                    value: 'someAddress',
                },
            }, mockContext),
            accept: true,
        })).rejects.toThrow('The Authorization Request has expired');
    }));
    test('should throw an error if the passed account is already part of an Identity', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createTxStub('multiSig', 'acceptMultisigSignerAsKey');
        const identity = mocks_1.entityMockUtils.getIdentityInstance();
        const target = mocks_1.entityMockUtils.getAccountInstance({
            address: 'someAddress',
            getIdentity: identity,
        });
        let error;
        try {
            yield consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
                authRequest: new internal_1.AuthorizationRequest({
                    target,
                    issuer: mocks_1.entityMockUtils.getIdentityInstance(),
                    authId,
                    expiry: null,
                    data: {
                        type: types_1.AuthorizationType.AddMultiSigSigner,
                        value: 'someAddress',
                    },
                }, mockContext),
                accept: true,
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The target Account is already part of an Identity');
    }));
    test('should add a acceptMultisigSignerAsKey transaction to the queue if the target is an Account', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('multiSig', 'acceptMultisigSignerAsKey');
        const issuer = mocks_1.entityMockUtils.getIdentityInstance();
        const target = mocks_1.entityMockUtils.getAccountInstance({
            address: 'someAddress',
            getIdentity: null,
        });
        yield consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
            authRequest: new internal_1.AuthorizationRequest({
                target,
                issuer,
                authId,
                expiry: null,
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                    value: 'someAccount',
                },
            }, mockContext),
            accept: true,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, { paidForBy: issuer }, rawAuthId);
    }));
    test('should add a acceptMultisigSignerAsIdentity transaction to the queue if the target is an Identity', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('multiSig', 'acceptMultisigSignerAsIdentity');
        const issuer = mocks_1.entityMockUtils.getIdentityInstance();
        const target = mocks_1.entityMockUtils.getIdentityInstance({ did: 'someOtherDid' });
        yield consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
            authRequest: new internal_1.AuthorizationRequest({
                target,
                issuer,
                authId,
                expiry: null,
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                    value: 'someAccount',
                },
            }, mockContext),
            accept: true,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, { paidForBy: issuer }, rawAuthId);
    }));
    test('should add a removeAuthorization transaction to the queue if accept is set to false', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('identity', 'removeAuthorization');
        const issuer = mocks_1.entityMockUtils.getIdentityInstance();
        let target = mocks_1.entityMockUtils.getIdentityInstance({ did: 'someOtherDid' });
        const rawSignatory = mocks_1.dsMockUtils.createMockSignatory({
            Identity: mocks_1.dsMockUtils.createMockIdentityId(target.did),
        });
        sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory').returns(rawSignatory);
        yield consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
            authRequest: new internal_1.AuthorizationRequest({
                target,
                issuer,
                authId,
                expiry: null,
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                    value: 'someAddress',
                },
            }, mockContext),
            accept: false,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawSignatory, rawAuthId, rawFalse);
        target = mocks_1.entityMockUtils.getAccountInstance({ address: targetAddress });
        yield consumeAddMultiSigSignerAuthorization_1.prepareConsumeAddMultiSigSignerAuthorization.call(proc, {
            authRequest: new internal_1.AuthorizationRequest({
                target,
                issuer,
                authId,
                expiry: null,
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                    value: 'someAddress',
                },
            }, mockContext),
            accept: false,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, { paidForBy: issuer }, rawSignatory, rawAuthId, rawTrue);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const { address } = mockContext.getCurrentAccount();
            const constructorParams = {
                authId,
                expiry: null,
                target: mocks_1.entityMockUtils.getAccountInstance({ address }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid1' }),
                data: {
                    type: types_1.AuthorizationType.AddMultiSigSigner,
                },
            };
            const args = {
                authRequest: new internal_1.AuthorizationRequest(constructorParams, mockContext),
                accept: true,
            };
            const boundFunc = consumeAddMultiSigSignerAuthorization_1.getAuthorization.bind(proc);
            let result = yield boundFunc(args);
            expect(result).toEqual({
                roles: true,
                permissions: {
                    transactions: [types_1.TxTags.multiSig.AcceptMultisigSignerAsKey],
                },
            });
            args.authRequest.target = mocks_1.entityMockUtils.getIdentityInstance({
                did: 'notTheCurrentIdentity',
            });
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    currentIdentityIsEqual: false,
                },
            });
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: '"AddMultiSigSigner" Authorization Requests can only be accepted by the target Signer',
                permissions: {
                    transactions: [types_1.TxTags.multiSig.AcceptMultisigSignerAsIdentity],
                },
            });
            args.accept = false;
            args.authRequest.issuer = yield mockContext.getCurrentIdentity();
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    currentIdentityIsEqual: true,
                },
            });
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: true,
                permissions: {
                    transactions: [types_1.TxTags.identity.RemoveAuthorization],
                },
            });
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    currentIdentityIsEqual: false,
                },
            });
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: '"AddMultiSigSigner" Authorization Request can only be removed by the issuing Identity or the target Signer',
                permissions: {
                    transactions: [types_1.TxTags.identity.RemoveAuthorization],
                },
            });
            mockContext.getCurrentAccount.returns(mocks_1.entityMockUtils.getAccountInstance({ address, getIdentity: null }));
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: '"AddMultiSigSigner" Authorization Request can only be removed by the issuing Identity or the target Signer',
                permissions: {
                    transactions: [types_1.TxTags.identity.RemoveAuthorization],
                },
            });
            args.authRequest.target = mocks_1.entityMockUtils.getAccountInstance({ address, getIdentity: null });
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: true,
            });
        }));
    });
});
//# sourceMappingURL=consumeAddMultiSigSignerAuthorization.js.map