"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.prepareInviteAccount = void 0;
const utils_1 = require("./utils");
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
function prepareInviteAccount(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { targetAccount, permissions: permissionsLike, expiry = null } = args;
        const identity = yield context.getSigningIdentity();
        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_1.ErrorCode.UnmetPrerequisite,
                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_1.AuthorizationType.JoinIdentity);
        });
        if (hasPendingAuth) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.NoDataChange,
                message: 'The target Account already has a pending invitation to join this Identity',
            });
        }
        const rawSignatory = conversion_1.signerValueToSignatory({ type: types_1.SignerType.Account, value: address }, context);
        let authorizationValue = {
            assets: { type: types_1.PermissionType.Include, values: [] },
            transactions: { type: types_1.PermissionType.Include, values: [] },
            transactionGroups: [],
            portfolios: { type: types_1.PermissionType.Include, values: [] },
        };
        if (permissionsLike) {
            authorizationValue = conversion_1.permissionsLikeToPermissions(permissionsLike, context);
        }
        const authRequest = {
            type: types_1.AuthorizationType.JoinIdentity,
            value: authorizationValue,
        };
        const rawAuthorizationData = conversion_1.authorizationToAuthorizationData(authRequest, context);
        const rawExpiry = internal_2.optionize(conversion_1.dateToMoment)(expiry, context);
        const [auth] = this.addTransaction({
            transaction: tx.identity.addAuthorization,
            resolvers: [utils_1.createAuthorizationResolver(authRequest, identity, account, expiry, context)],
            args: [rawSignatory, rawAuthorizationData, rawExpiry],
        });
        return auth;
    });
}
exports.prepareInviteAccount = prepareInviteAccount;
/**
 * @hidden
 */
const inviteAccount = () => new internal_1.Procedure(prepareInviteAccount, {
    permissions: {
        transactions: [types_1.TxTags.identity.AddAuthorization],
        assets: [],
        portfolios: [],
    },
});
exports.inviteAccount = inviteAccount;
//# sourceMappingURL=inviteAccount.js.map