"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 linkCaDocs_1 = require("../linkCaDocs");
const mocks_1 = require("../../../testUtils/mocks");
const utils_1 = require("../../../types/utils");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('linkCaDocs procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let ticker;
    let id;
    let documents;
    let rawTicker;
    let rawDocuments;
    let rawDocumentIds;
    let documentEntries;
    let args;
    let rawCaId;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        ticker = 'someTicker';
        id = new bignumber_js_1.default(1);
        documents = [
            {
                name: 'someDocument',
                uri: 'someUri',
                contentHash: '0x01',
            },
            {
                name: 'otherDocument',
                uri: 'otherUri',
                contentHash: '0x02',
            },
        ];
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawDocuments = documents.map(({ name, uri, contentHash, type, filedAt }) => mocks_1.dsMockUtils.createMockDocument({
            name: mocks_1.dsMockUtils.createMockDocumentName(name),
            uri: mocks_1.dsMockUtils.createMockDocumentUri(uri),
            /* eslint-disable @typescript-eslint/naming-convention */
            content_hash: mocks_1.dsMockUtils.createMockDocumentHash({
                H128: mocks_1.dsMockUtils.createMockU8aFixed(contentHash, true),
            }),
            doc_type: mocks_1.dsMockUtils.createMockOption(type ? mocks_1.dsMockUtils.createMockDocumentType(type) : null),
            filing_date: mocks_1.dsMockUtils.createMockOption(filedAt ? mocks_1.dsMockUtils.createMockMoment(filedAt.getTime()) : null),
            /* eslint-enabled @typescript-eslint/naming-convention */
        }));
        documentEntries = [];
        rawDocumentIds = [];
        rawDocuments.forEach((doc, index) => {
            const rawId = mocks_1.dsMockUtils.createMockU32(index);
            documentEntries.push(utils_1.tuple([rawTicker, rawId], doc));
            rawDocumentIds.push(rawId);
        });
        args = {
            id,
            ticker,
            documents,
        };
        // eslint-disable-next-line @typescript-eslint/naming-convention
        rawCaId = mocks_1.dsMockUtils.createMockCAId({ ticker, local_id: id.toNumber() });
        sinon_1.default.stub(utilsConversionModule, 'corporateActionIdentifierToCaId').returns(rawCaId);
    });
    let addTransactionStub;
    let linkCaDocTransaction;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mocks_1.dsMockUtils.createQueryStub('asset', 'assetDocuments', {
            entries: [documentEntries[0], documentEntries[1]],
        });
        linkCaDocTransaction = mocks_1.dsMockUtils.createTxStub('corporateAction', 'linkCaDoc');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
    });
    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 some of the provided documents are not associated to the Security Token', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const name = 'customName';
        let error;
        try {
            yield linkCaDocs_1.prepareLinkCaDocs.call(proc, {
                id,
                ticker,
                documents: [
                    documents[0],
                    {
                        name,
                        uri: 'someUri',
                        contentHash: 'someHash',
                    },
                ],
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('Some of the provided documents are not associated with the Security Token');
        expect(error.data.documents.length).toEqual(1);
        expect(error.data.documents[0].name).toEqual(name);
    }));
    test('should add a link ca doc transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        yield linkCaDocs_1.prepareLinkCaDocs.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, linkCaDocTransaction, {}, rawCaId, rawDocumentIds);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = linkCaDocs_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    transactions: [types_1.TxTags.corporateAction.LinkCaDoc],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=linkCaDocs.js.map