"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 modifyAssetTrustedClaimIssuers_1 = require("../modifyAssetTrustedClaimIssuers");
const mocks_1 = require("../../../testUtils/mocks");
const internal_1 = require("../../../types/internal");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
describe('modifyAssetTrustedClaimIssuers procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let trustedClaimIssuerToTrustedIssuerStub;
    let stringToIdentityIdStub;
    let identityIdToStringStub;
    let trustedClaimIssuerStub;
    let ticker;
    let claimIssuerDids;
    let claimIssuers;
    let rawTicker;
    let rawClaimIssuers;
    let args;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        trustedClaimIssuerToTrustedIssuerStub = sinon_1.default.stub(utilsConversionModule, 'trustedClaimIssuerToTrustedIssuer');
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
        identityIdToStringStub = sinon_1.default.stub(utilsConversionModule, 'identityIdToString');
        ticker = 'someTicker';
        claimIssuerDids = ['aDid', 'otherDid', 'differentDid'];
        claimIssuers = claimIssuerDids.map(did => ({
            identity: mocks_1.entityMockUtils.getIdentityInstance({ did }),
            trustedFor: null,
        }));
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawClaimIssuers = claimIssuerDids.map(did => mocks_1.dsMockUtils.createMockTrustedIssuer({
            issuer: mocks_1.dsMockUtils.createMockIdentityId(did),
            // eslint-disable-next-line @typescript-eslint/naming-convention
            trusted_for: mocks_1.dsMockUtils.createMockTrustedFor('Any'),
        }));
        args = {
            ticker,
        };
    });
    let addBatchTransactionStub;
    let removeDefaultTrustedClaimIssuerTransaction;
    let addDefaultTrustedClaimIssuerTransaction;
    beforeEach(() => {
        addBatchTransactionStub = mocks_1.procedureMockUtils.getAddBatchTransactionStub();
        trustedClaimIssuerStub = mocks_1.dsMockUtils.createQueryStub('complianceManager', 'trustedClaimIssuer', {
            returnValue: [],
        });
        removeDefaultTrustedClaimIssuerTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'removeDefaultTrustedClaimIssuer');
        addDefaultTrustedClaimIssuerTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'addDefaultTrustedClaimIssuer');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        claimIssuerDids.forEach((did, index) => {
            trustedClaimIssuerToTrustedIssuerStub
                .withArgs(sinon_1.default.match({ identity: sinon_1.default.match({ did }) }), mockContext)
                .returns(rawClaimIssuers[index]);
        });
        claimIssuers.forEach((issuer, index) => {
            identityIdToStringStub.withArgs(rawClaimIssuers[index].issuer).returns(issuer.identity.did);
            stringToIdentityIdStub
                .withArgs(utilsConversionModule.signerToString(issuer.identity), mockContext)
                .returns(rawClaimIssuers[index].issuer);
        });
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the new list is the same as the current one (set)', () => {
        const alternativeClaimIssuers = rawClaimIssuers.map(({ issuer }) => mocks_1.dsMockUtils.createMockTrustedIssuer({
            issuer,
            // eslint-disable-next-line @typescript-eslint/naming-convention
            trusted_for: mocks_1.dsMockUtils.createMockTrustedFor({ Specific: [] }),
        }));
        trustedClaimIssuerStub.withArgs(rawTicker).returns(alternativeClaimIssuers);
        claimIssuerDids.forEach((did, index) => {
            trustedClaimIssuerToTrustedIssuerStub
                .withArgs(sinon_1.default.match({ identity: sinon_1.default.match({ did }) }), mockContext)
                .returns(alternativeClaimIssuers[index]);
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers: claimIssuers.map(({ identity }) => ({ identity, trustedFor: [] })), operation: internal_1.TrustedClaimIssuerOperation.Set }))).rejects.toThrow('The supplied claim issuer list is equal to the current one');
    });
    test("should throw an error if some of the supplied dids don't exist", () => __awaiter(void 0, void 0, void 0, function* () {
        const nonExistentDid = claimIssuerDids[1];
        mocks_1.dsMockUtils.configureMocks({ contextOptions: { invalidDids: [nonExistentDid] } });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let error;
        try {
            yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers, operation: internal_1.TrustedClaimIssuerOperation.Set }));
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('Some of the supplied Identities do not exist');
        expect(error.data).toMatchObject({ nonExistentDids: [nonExistentDid] });
    }));
    test('should add a transaction to remove the current claim issuers and another one to add the ones in the input (set)', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = rawClaimIssuers.slice(0, -1);
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers, operation: internal_1.TrustedClaimIssuerOperation.Set }));
        sinon_1.default.assert.calledWith(addBatchTransactionStub, {
            transactions: [
                ...currentClaimIssuers.map(({ issuer }) => ({
                    transaction: removeDefaultTrustedClaimIssuerTransaction,
                    args: [rawTicker, issuer],
                })),
                ...rawClaimIssuers.map(issuer => ({
                    transaction: addDefaultTrustedClaimIssuerTransaction,
                    args: [rawTicker, issuer],
                })),
            ],
        });
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should not add a remove claim issuers transaction if there are no default claim issuers set on the Asset (set)', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers: claimIssuers.map(({ identity, trustedFor }) => ({
                identity: utilsConversionModule.signerToString(identity),
                trustedFor,
            })), operation: internal_1.TrustedClaimIssuerOperation.Set }));
        sinon_1.default.assert.calledWith(addBatchTransactionStub.firstCall, {
            transactions: rawClaimIssuers.map(issuer => ({
                transaction: addDefaultTrustedClaimIssuerTransaction,
                args: [rawTicker, issuer],
            })),
        });
        sinon_1.default.assert.calledOnce(addBatchTransactionStub);
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should not add an add claim issuers transaction if there are no claim issuers passed as arguments (set)', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = rawClaimIssuers.slice(0, -1);
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers: [], operation: internal_1.TrustedClaimIssuerOperation.Set }));
        sinon_1.default.assert.calledWith(addBatchTransactionStub.firstCall, {
            transactions: currentClaimIssuers.map(({ issuer }) => ({
                transaction: removeDefaultTrustedClaimIssuerTransaction,
                args: [rawTicker, issuer],
            })),
        });
        sinon_1.default.assert.calledOnce(addBatchTransactionStub);
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should throw an error if trying to remove an Identity that is not a trusted claim issuer', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = [];
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let error;
        try {
            yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers: claimIssuerDids, operation: internal_1.TrustedClaimIssuerOperation.Remove }));
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('One or more of the supplied Identities are not Trusted Claim Issuers');
        expect(error.data).toMatchObject({ notPresent: claimIssuerDids });
    }));
    test('should add a transaction to remove the supplied Trusted Claim Issuers (remove)', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = rawClaimIssuers;
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers: claimIssuerDids, operation: internal_1.TrustedClaimIssuerOperation.Remove }));
        sinon_1.default.assert.calledWith(addBatchTransactionStub, {
            transactions: currentClaimIssuers.map(({ issuer }) => ({
                transaction: removeDefaultTrustedClaimIssuerTransaction,
                args: [rawTicker, issuer],
            })),
        });
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should throw an error if trying to add an Identity that is already a Trusted Claim Issuer', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = rawClaimIssuers;
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        let error;
        try {
            yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers, operation: internal_1.TrustedClaimIssuerOperation.Add }));
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('One or more of the supplied Identities already are Trusted Claim Issuers');
        expect(error.data).toMatchObject({ present: claimIssuerDids });
    }));
    test('should add a transaction to add the supplied Trusted Claim Issuers (add)', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentClaimIssuers = [];
        trustedClaimIssuerStub.withArgs(rawTicker).returns(currentClaimIssuers);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield modifyAssetTrustedClaimIssuers_1.prepareModifyAssetTrustedClaimIssuers.call(proc, Object.assign(Object.assign({}, args), { claimIssuers, operation: internal_1.TrustedClaimIssuerOperation.Add }));
        sinon_1.default.assert.calledWith(addBatchTransactionStub, {
            transactions: rawClaimIssuers.map(issuer => ({
                transaction: addDefaultTrustedClaimIssuerTransaction,
                args: [rawTicker, issuer],
            })),
        });
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = modifyAssetTrustedClaimIssuers_1.getAuthorization.bind(proc);
            const asset = expect.objectContaining({ ticker });
            expect(boundFunc({ ticker, operation: internal_1.TrustedClaimIssuerOperation.Add, claimIssuers: [] })).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.complianceManager.AddDefaultTrustedClaimIssuer],
                    assets: [asset],
                    portfolios: [],
                },
            });
            expect(boundFunc({ ticker, operation: internal_1.TrustedClaimIssuerOperation.Remove, claimIssuers: [] })).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.complianceManager.RemoveDefaultTrustedClaimIssuer],
                    assets: [asset],
                    portfolios: [],
                },
            });
            expect(boundFunc({ ticker, operation: internal_1.TrustedClaimIssuerOperation.Set, claimIssuers: [] })).toEqual({
                permissions: {
                    transactions: [
                        types_1.TxTags.complianceManager.RemoveDefaultTrustedClaimIssuer,
                        types_1.TxTags.complianceManager.AddDefaultTrustedClaimIssuer,
                    ],
                    assets: [asset],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=modifyAssetTrustedClaimIssuers.js.map