"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.inviteAccount = exports.getAuthorization = exports.prepareInviteAccount = void 0;
const types_1 = require("../../polkadot/types");
const internal_1 = require("../../internal");
const types_2 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareInviteAccount(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { targetAccount, permissions: permissionsLike, expiry, identity } = args;
        const address = conversion_1.signerToString(targetAccount);
        let account;
        if (targetAccount instanceof internal_1.Account) {
            account = targetAccount;
        }
        else {
            account = new internal_1.Account({ address: targetAccount }, context);
        }
        const [authorizationRequests, existingIdentity] = yield Promise.all([
            identity.authorizations.getSent(),
            account.getIdentity(),
        ]);
        if (existingIdentity) {
            throw new internal_1.PolymeshError({
                code: types_2.ErrorCode.ValidationError,
                message: 'The target Account is already part of an Identity',
            });
        }
        const hasPendingAuth = !!authorizationRequests.data.find(authorizationRequest => {
            const { target, data: { type }, } = authorizationRequest;
            return (conversion_1.signerToString(target) === address &&
                !authorizationRequest.isExpired() &&
                type === types_2.AuthorizationType.JoinIdentity);
        });
        if (hasPendingAuth) {
            throw new internal_1.PolymeshError({
                code: types_2.ErrorCode.ValidationError,
                message: 'The target Account already has a pending invitation to join this Identity',
            });
        }
        const rawSignatory = conversion_1.signerValueToSignatory({ type: types_2.SignerType.Account, value: address }, context);
        let authorizationValue = {
            tokens: { type: types_2.PermissionType.Include, values: [] },
            transactions: { type: types_2.PermissionType.Include, values: [] },
            transactionGroups: [],
            portfolios: { type: types_2.PermissionType.Include, values: [] },
        };
        if (permissionsLike) {
            authorizationValue = conversion_1.permissionsLikeToPermissions(permissionsLike, context);
        }
        const rawAuthorizationData = conversion_1.authorizationToAuthorizationData({
            type: types_2.AuthorizationType.JoinIdentity,
            value: authorizationValue,
        }, context);
        const rawExpiry = expiry ? conversion_1.dateToMoment(expiry, context) : null;
        this.addTransaction(tx.identity.addAuthorization, {}, rawSignatory, rawAuthorizationData, rawExpiry);
    });
}
exports.prepareInviteAccount = prepareInviteAccount;
/**
 * @hidden
 */
function getAuthorization({ identity: { did } }) {
    return {
        roles: [{ type: types_2.RoleType.Identity, did }],
        permissions: {
            transactions: [types_1.TxTags.identity.AddAuthorization],
            tokens: [],
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const inviteAccount = () => new internal_1.Procedure(prepareInviteAccount, getAuthorization);
exports.inviteAccount = inviteAccount;
//# sourceMappingURL=inviteAccount.js.map