"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const cli_common_1 = require("../../cli-common");
const command_base_exec_1 = require("../../command-base-exec");
class EnvironmentDelete extends command_base_exec_1.CommandBaseExec {
    constructor() {
        super(...arguments);
        this.infrxAliases = ["infrx:environment:delete", "infrx:enviro:delete"];
    }
    captureArgs() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(EnvironmentDelete);
            let partial = {};
            if (args.name)
                partial.name = args.name;
            if (flags.enterprise)
                partial.enterprise = flags.enterprise;
            const takeDefaults = (_a = flags['take-defaults']) !== null && _a !== void 0 ? _a : false;
            return [partial, takeDefaults];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!partial.name)
                throw new Error("Environment name is required.");
            const ent = rootMap.enterprises.find(e => e.name === partial.enterprise);
            if (!ent)
                throw new Error(`Enterprise "${partial.enterprise}" not found.`);
            const env = ent.environments.find(e => e.name === partial.name);
            if (!env)
                throw new Error(`Environment "${partial.name}" does not exist in enterprise "${partial.enterprise}".`);
            if (!env.id)
                throw new Error(`Environment "${partial.name}" does not have an id and cannot be deleted.`);
            return {
                enterprise: partial.enterprise,
                name: partial.name,
                id: env.id,
            };
        });
    }
    buildCandidate_interactively(partial, rootMap, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const ent = rootMap.enterprises.find(e => e.name === partial.enterprise);
            if (!ent)
                throw new Error(`Enterprise "${partial.enterprise}" not found.`);
            const envNames = ent.environments.map(e => e.name);
            if (envNames.length === 0)
                throw new Error(`Enterprise "${partial.enterprise}" has no environments to delete.`);
            partial.name = yield this.setName(partial.name, envNames, takeDefaults);
            const env = ent.environments.find(e => e.name === partial.name);
            if (!(env === null || env === void 0 ? void 0 : env.id))
                throw new Error(`Environment "${partial.name}" does not have an id and cannot be deleted.`);
            return {
                enterprise: partial.enterprise,
                name: partial.name,
                id: env.id,
            };
        });
    }
    setName(userInput, choices, takeDefaults) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let output;
            if (userInput != undefined) {
                if (choices.includes(userInput)) {
                    output = userInput;
                    this._ui.userMessage("Continuing with ".concat(this._styler.hilite(output)));
                }
                else {
                    this._ui.userMessage(this._styler.colorWarning(`"${userInput}" is not a valid environment name; please select from the list below.`));
                }
            }
            else if (choices.length === 1) {
                const sole = choices[0];
                if (takeDefaults) {
                    output = sole;
                    this._ui.userMessage("Continuing with ".concat(this._styler.hilite(output)));
                }
                else {
                    if (yield this._ui.promptConfirm("confirmName", `Delete environment: ${this._styler.hilite(sole)}?`, false)) {
                        output = sole;
                    }
                }
            }
            if (output == undefined) {
                output = yield this._ui.promptSelect("name", "Select an environment to delete:", choices);
            }
            return output;
        });
    }
    buildCommandString(candidate, cmd) {
        cmd.push(candidate.name);
        cmd.push("--enterprise", candidate.enterprise);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a, _b;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this._ui.startSpinner(`Deleting environment [${candidate.enterprise}/${candidate.name}]...`);
            const result = yield this._codiacApi.Environment.tryDelete({ id: candidate.id });
            this._ui.stopSpinner(result.success ? "Completed" : "Failed");
            if (result.error) {
                this._ui.userMessage(`${this._styler.colorCritical("ERROR")}: ${(_a = result.message) !== null && _a !== void 0 ? _a : ""}; ${result.error.message}`);
                throw result.error;
            }
            else if (!result.success) {
                this._ui.userMessage(`FAILED: ${(_b = result.message) !== null && _b !== void 0 ? _b : "Environment deletion failed without error."}`);
            }
            else {
                this._ui.userMessage(`${this._styler.colorGood("SUCCESS")}: Environment [${this._styler.hilite(candidate.name)}] deleted from enterprise [${candidate.enterprise}].`);
            }
        });
    }
}
exports.default = EnvironmentDelete;
EnvironmentDelete.description = 'Deletes an existing environment from a given enterprise. Returns an error if the environment does not exist.';
EnvironmentDelete.aliases = ["enviro:delete", "infrx:environment:delete", "infrx:enviro:delete"];
// static hidden = true;
EnvironmentDelete.args = {
    name: core_1.Args.string({ required: false, description: 'The name of the environment to delete.' }),
};
EnvironmentDelete.examples = [
    { description: 'Delete an environment interactively.', command: '<%= config.bin %> <%= command.id %>' },
    { description: 'Delete a named environment interactively.', command: '<%= config.bin %> <%= command.id %> dev' },
    { description: 'Delete an environment non-interactively.', command: '<%= config.bin %> <%= command.id %> dev --enterprise main --silent' },
    { description: 'Renders the equivalent silent command and then executes.', command: '<%= config.bin %> <%= command.id %> dev --enterprise main --echo' },
    { description: 'Renders the equivalent silent command without executing.', command: '<%= config.bin %> <%= command.id %> dev --enterprise main --to-script' },
];
EnvironmentDelete.flags = Object.assign(Object.assign({ enterprise: core_1.Flags.string({ char: 'e', required: false, description: 'Code name of the enterprise from which to delete the environment.' }) }, cli_common_1.commandBase.globalFlags), { help: core_1.Flags.help({ char: 'h' }), silent: core_1.Flags.boolean({ exclusive: ["echo", "to-script"], description: 'Executes without any user interaction; fails on missing or invalid arguments.' }), echo: core_1.Flags.boolean({ exclusive: ["to-script", "silent"], description: 'Renders the equivalent non-interactive command for future use before executing.' }), "to-script": core_1.Flags.boolean({ exclusive: ["echo", "silent"], description: 'Renders the equivalent non-interactive command without executing it.' }), "take-defaults": core_1.Flags.boolean({ exclusive: ["silent"], description: 'Accepts default values without prompting for confirmation. (Irrelevant in --silent mode).' }) });
//# sourceMappingURL=delete.js.map