"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.deletePortfolio = exports.getAuthorization = exports.prepareDeletePortfolio = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
/**
 * @hidden
 */
function prepareDeletePortfolio(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx: { portfolio }, }, }, context, } = this;
        const { did, id } = args;
        const numberedPortfolio = new internal_1.NumberedPortfolio({ did, id }, context);
        const rawPortfolioNumber = conversion_1.bigNumberToU64(id, context);
        const [exists, portfolioBalances] = yield Promise.all([
            numberedPortfolio.exists(),
            numberedPortfolio.getAssetBalances(),
        ]);
        if (!exists) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.DataUnavailable,
                message: "The Portfolio doesn't exist",
            });
        }
        if (portfolioBalances.some(({ total }) => total.gt(0))) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.EntityInUse,
                message: 'Only empty Portfolios can be deleted',
            });
        }
        this.addTransaction({
            transaction: portfolio.deletePortfolio,
            args: [rawPortfolioNumber],
        });
    });
}
exports.prepareDeletePortfolio = prepareDeletePortfolio;
/**
 * @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.portfolio.DeletePortfolio],
            portfolios: [conversion_1.portfolioLikeToPortfolio({ identity: did, id }, context)],
            assets: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const deletePortfolio = () => new internal_1.Procedure(prepareDeletePortfolio, getAuthorization);
exports.deletePortfolio = deletePortfolio;
//# sourceMappingURL=deletePortfolio.js.map