"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 setCustodian_1 = require("../setCustodian");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/DefaultPortfolio', require("../../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
jest.mock('~/api/entities/NumberedPortfolio', require("../../../testUtils/mocks/entities").mockNumberedPortfolioModule('~/api/entities/NumberedPortfolio'));
jest.mock('~/api/entities/AuthorizationRequest', require("../../../testUtils/mocks/entities").mockAuthorizationRequestModule('~/api/entities/AuthorizationRequest'));
describe('setCustodian procedure', () => {
    let mockContext;
    let addTransactionStub;
    let authorizationToAuthorizationDataStub;
    let dateToMomentStub;
    let signerToStringStub;
    let signerValueToSignatoryStub;
    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');
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        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();
    });
    test('should throw an error if the passed account has a pending authorization to accept', () => {
        const did = 'someDid';
        const args = { targetIdentity: 'targetIdentity', did };
        const target = mocks_1.entityMockUtils.getIdentityInstance({ did: args.targetIdentity });
        const signer = mocks_1.entityMockUtils.getAccountInstance({ address: 'someFakeAccount' });
        const fakePortfolio = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did });
        const receivedAuthorizations = [
            mocks_1.entityMockUtils.getAuthorizationRequestInstance({
                target,
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did }),
                authId: new bignumber_js_1.default(1),
                expiry: null,
                data: { type: types_2.AuthorizationType.PortfolioCustody, value: fakePortfolio },
            }),
        ];
        mocks_1.entityMockUtils.configureMocks({
            identityOptions: {
                authorizations: {
                    getReceived: receivedAuthorizations,
                },
            },
        });
        signerToStringStub.withArgs(signer).returns(signer.address);
        signerToStringStub.withArgs(args.targetIdentity).returns(args.targetIdentity);
        signerToStringStub.withArgs(target).returns(args.targetIdentity);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(setCustodian_1.prepareSetCustodian.call(proc, args)).rejects.toThrow("The target Identity already has a pending invitation to be the Portfolio's custodian");
    });
    test('should add an add authorization transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const did = 'someDid';
        const id = new bignumber_js_1.default(1);
        const expiry = new Date('1/1/2040');
        const args = { targetIdentity: 'targetIdentity', did };
        const target = mocks_1.entityMockUtils.getIdentityInstance({ did: args.targetIdentity });
        const signer = mocks_1.entityMockUtils.getAccountInstance({ address: 'someFakeAccount' });
        const rawSignatory = mocks_1.dsMockUtils.createMockSignatory({
            Account: mocks_1.dsMockUtils.createMockAccountId('someAccountId'),
        });
        const rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
        const rawPortfolioKind = mocks_1.dsMockUtils.createMockPortfolioKind({
            User: mocks_1.dsMockUtils.createMockU64(id.toNumber()),
        });
        const rawAuthorizationData = mocks_1.dsMockUtils.createMockAuthorizationData({
            PortfolioCustody: mocks_1.dsMockUtils.createMockPortfolioId({ did: rawDid, kind: rawPortfolioKind }),
        });
        const rawExpiry = mocks_1.dsMockUtils.createMockMoment(expiry.getTime());
        const fakePortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({ isEqual: false });
        const receivedAuthorizations = [
            mocks_1.entityMockUtils.getAuthorizationRequestInstance({
                target,
                issuer: mocks_1.entityMockUtils.getIdentityInstance(),
                authId: new bignumber_js_1.default(1),
                expiry: null,
                data: { type: types_2.AuthorizationType.PortfolioCustody, value: fakePortfolio },
            }),
        ];
        mocks_1.entityMockUtils.configureMocks({
            identityOptions: {
                authorizations: {
                    getReceived: receivedAuthorizations,
                },
            },
            defaultPortfolioOptions: {
                isEqual: false,
            },
            numberedPortfolioOptions: {
                isEqual: false,
            },
        });
        signerToStringStub.withArgs(signer).returns(signer.address);
        signerToStringStub.withArgs(args.targetIdentity).returns(args.targetIdentity);
        signerToStringStub.withArgs(target).returns('someValue');
        signerValueToSignatoryStub
            .withArgs({ type: types_2.SignerType.Identity, value: args.targetIdentity }, 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 setCustodian_1.prepareSetCustodian.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({ resolvers: sinon_1.default.match.array }), rawSignatory, rawAuthorizationData, null);
        yield setCustodian_1.prepareSetCustodian.call(proc, Object.assign(Object.assign({}, args), { id, expiry }));
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, sinon_1.default.match({ resolvers: sinon_1.default.match.array }), rawSignatory, rawAuthorizationData, rawExpiry);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = setCustodian_1.getAuthorization.bind(proc);
            const id = new bignumber_js_1.default(1);
            const did = 'someDid';
            let args = {
                id,
                did,
            };
            let portfolioId = { did: args.did, number: args.id };
            expect(boundFunc(args)).toEqual({
                roles: [{ type: types_2.RoleType.PortfolioCustodian, portfolioId }],
                permissions: {
                    transactions: [types_1.TxTags.identity.AddAuthorization],
                    portfolios: [mocks_1.entityMockUtils.getNumberedPortfolioInstance({ did, id })],
                    tokens: [],
                },
            });
            args = {
                did,
            };
            portfolioId = { did: args.did };
            expect(boundFunc(args)).toEqual({
                roles: [{ type: types_2.RoleType.PortfolioCustodian, portfolioId }],
                permissions: {
                    transactions: [types_1.TxTags.identity.AddAuthorization],
                    portfolios: [mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did })],
                    tokens: [],
                },
            });
        });
    });
});
//# sourceMappingURL=setCustodian.js.map