"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const contracts_1 = require("@codiac.io/codiac-common/contracts");
const security_1 = require("@codiac.io/codiac-common/security");
const config_ui_utils_1 = require("../../../uilogic/config-ui-utils");
const command_base_exec_tenant_1 = require("../../../command-base-exec-tenant");
class AuthRoleDelete extends command_base_exec_tenant_1.CommandBaseExecTenant {
    constructor() {
        super(...arguments);
        this.adminOnly = true;
    }
    captureArgs() {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(AuthRoleDelete);
            let partial = {};
            if (args.name && flags.id) {
                throw new Error("You must specify either the role name argument or the --id flag, not both.");
            }
            if (args.name)
                partial.name = args.name;
            if (flags.id)
                partial.id = flags.id;
            // ---------------------------------------------------------------
            // TODO: move everything from here down into the base class
            // ---------------------------------------------------------------
            const interactionMode = (this.pipedInput) ? config_ui_utils_1.InteractionModes.silent : (_b = (_a = undefined !== null && undefined !== void 0 ? undefined : (flags.echo ? config_ui_utils_1.InteractionModes.echo : undefined)) !== null && _a !== void 0 ? _a : (flags["to-script"] ? config_ui_utils_1.InteractionModes.toscript : undefined)) !== null && _b !== void 0 ? _b : (flags.silent ? config_ui_utils_1.InteractionModes.silent : undefined);
            const takeDefaults = flags['take-defaults'];
            return [partial, interactionMode, takeDefaults];
        });
    }
    // /** Throws on invalid */
    // private validate(partial: Partial<IAuthRoleDef>): void {
    //   if (partial.name == undefined || _.isEmpty(partial.name)) throw new Error("Missing name");
    //   let rxName = /^[a-zA-Z][a-zA-Z0-9-]{2,50}$/;
    //   if (!rxName.test(partial.name)) throw new Error("Invalid name: must be 3- to 50-character string of alphanumerics and hyphens, starting with a letter.");
    // }
    buildCandidate_silently(partial) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (partial.id == undefined && partial.name == undefined)
                throw new Error("Must specify either id or name.");
            let candidate = {};
            if (partial.id) {
                candidate.id = partial.id;
            }
            else if (partial.name) {
                if (partial.name == security_1.AUTH_ADMIN_ROLE_NAME)
                    throw new Error("The Built-in '".concat(security_1.AUTH_ADMIN_ROLE_NAME, "' role cannot be deleted."));
                let rxName = /^[a-zA-Z][a-zA-Z0-9-]{2,50}$/;
                if (!rxName.test(partial.name))
                    throw new Error("Invalid name: must be 3- to 50-character string of alphanumerics and hyphens, starting with a letter.");
                candidate.name = partial.name;
            }
            return candidate;
        });
    }
    buildCandidate_interactively(partial, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return yield this.buildCandidate_silently(partial);
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.id) {
            cmd.push("--id", candidate.id);
        }
        else if (candidate.name) {
            cmd.push("--name", candidate.name);
        }
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let result = new contracts_1.SingleResult(false);
            if (candidate.id) {
                // result = await this._codiacApi.AuthRole.tryDelete({ id: candidate.id });
                let found = yield this._codiacApi.AuthRole.read({ id: candidate.id }, { throwNotFound: true });
                if (found.name == security_1.AUTH_ADMIN_ROLE_NAME)
                    throw new Error("The Built-in '".concat(security_1.AUTH_ADMIN_ROLE_NAME, "' role cannot be deleted."));
                // result = await this._codiacApi.AuthRole.tryDeleteWhere({ ids: [candidate.id], name: { $not: { $eq: AUTH_ADMIN_ROLE_NAME } } });
                result = yield this._codiacApi.Auth.RoleDelete({ id: candidate.id });
            }
            else if (candidate.name) {
                result = yield this._codiacApi.AuthRole.tryDeleteWhere({ name: { $eq: candidate.name } });
            }
            if (result.error)
                throw result.error;
            if (result.success) {
                this._ui.userMessage(this._styler.colorGood("Success! ").concat((_a = result.message) !== null && _a !== void 0 ? _a : "Deleted Role."));
            }
            else {
                this._ui.userMessage((_b = result.message) !== null && _b !== void 0 ? _b : "Failed to delete: Role not found.");
            }
            return;
        });
    }
}
exports.default = AuthRoleDelete;
AuthRoleDelete.description = 'Deletes an existing Role from the current tenant security context.  A role cannot be deleted if it is still assigned to an existing user or group.';
AuthRoleDelete.aliases = [];
AuthRoleDelete.examples = [
    '<%= config.bin %> <%= command.id %> -n deployer',
    '<%= config.bin %> <%= command.id %> --id abc123def456'
];
AuthRoleDelete.flags = {
    id: core_1.Flags.string({ required: false, exclusive: ["name"], description: 'System ID of the Role.' }),
    // TODO: Move these into the base class
    silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Non-Interactive mode; executes without any user interaction and fails on any missing or invalid arguments.' }),
    echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Echo interaction mode; renders the equivalent non-interactive cli command for future use before final execution.' }),
    "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Toscript interaction mode; renders the equivalent non-interactive cli command WITHOUT any execution.' }),
    "take-defaults": core_1.Flags.boolean({ exclusive: ["silent"], description: "Setting this to true prevents prompting for confirmation on parameters that were passed in or were automatically set to default values (Irrelevant in --silent mode).  This behavior does NOT apply to scenarios that the command needs to override invalid user input; such cases will always prompt for confirmation.  eg: when no argument was provided for file or type, and only one exists, the system will render the autoselected file unless this flag is set." })
};
AuthRoleDelete.args = {
    name: core_1.Args.string({ required: false, exclusive: ["id"], description: 'Name of the Role.' }),
};
//# sourceMappingURL=delete.js.map