"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setCustodian = exports.getAuthorization = exports.prepareSetCustodian = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareSetCustodian(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx: { identity }, }, }, context, } = this;
        const { targetIdentity, expiry, did, id } = args;
        const portfolio = conversion_1.portfolioIdToPortfolio({ did, number: id }, context);
        const targetDid = conversion_1.signerToString(targetIdentity);
        const target = new internal_1.Identity({ did: targetDid }, context);
        const [authorizationRequests, currentIdentity] = yield Promise.all([
            target.authorizations.getReceived({
                type: types_1.AuthorizationType.PortfolioCustody,
                includeExpired: false,
            }),
            context.getCurrentIdentity(),
        ]);
        const hasPendingAuth = !!authorizationRequests.find(authorizationRequest => {
            const { issuer, data } = authorizationRequest;
            const authorizationData = data;
            return currentIdentity.isEqual(issuer) && authorizationData.value.isEqual(portfolio);
        });
        if (hasPendingAuth) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.ValidationError,
                message: "The target Identity already has a pending invitation to be the Portfolio's custodian",
            });
        }
        const rawSignatory = conversion_1.signerValueToSignatory(conversion_1.signerToSignerValue(target), context);
        const rawAuthorizationData = conversion_1.authorizationToAuthorizationData({ type: types_1.AuthorizationType.PortfolioCustody, value: portfolio }, context);
        const rawExpiry = expiry ? conversion_1.dateToMoment(expiry, context) : null;
        this.addTransaction(identity.addAuthorization, {}, rawSignatory, rawAuthorizationData, rawExpiry);
    });
}
exports.prepareSetCustodian = prepareSetCustodian;
/**
 * @hidden
 */
function getAuthorization({ did, id }) {
    const { context } = this;
    const portfolioId = { did, number: id };
    return {
        roles: [{ type: types_1.RoleType.PortfolioCustodian, portfolioId }],
        permissions: {
            transactions: [types_1.TxTags.identity.AddAuthorization],
            portfolios: [conversion_1.portfolioIdToPortfolio({ did, number: id }, context)],
            tokens: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const setCustodian = () => new internal_1.Procedure(prepareSetCustodian, getAuthorization);
exports.setCustodian = setCustodian;
//# sourceMappingURL=setCustodian.js.map