"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MyTenantRequest = void 0;
const tslib_1 = require("tslib");
require("reflect-metadata");
const cli_common_1 = require("../../cli-common");
const core_1 = require("@oclif/core");
const command_base_exec_tenant_1 = require("../../command-base-exec-tenant");
const config_ui_utils_1 = require("../../uilogic/config-ui-utils");
class MyTenantRequest {
}
exports.MyTenantRequest = MyTenantRequest;
class EnterpriseCreate extends command_base_exec_tenant_1.CommandBaseExecTenant {
    buildCommandString(candidate, cmd) {
        cmd.push(candidate.enterprise_code);
        cmd.push("--silent");
        return cmd;
    }
    bootstrap() {
        super.bootstrap();
        // CloudProviderContextualizer.bootstrap(this.ioc);
    }
    captureArgs() {
        var _a, _b, _c;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { args, flags } = yield this.parse(EnterpriseCreate);
            let partial = {};
            if (args.code)
                partial.enterprise_code = args.code;
            const interactionMode = (_b = (_a = (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 = (_c = flags['take-defaults']) !== null && _c !== void 0 ? _c : false;
            return [partial, interactionMode, takeDefaults];
        });
    }
    validatePartial(partial) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            if (!partial.enterprise_code) {
                throw new Error("Enterprise code is required.");
            }
            return partial;
        });
    }
    getMyTenantSubscriptionId() {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            // Assemble and write
            // httpRestVerb.GET, "/auth/my-tenant(/)"
            let tenantResult = yield this._codiacApi.Auth.MyTenant({}); // , tenantCode: this._userCntx.currentTenantCode
            // let tenantResult = await this._codiacApi.Subscription.tryReadMany({ all: true }, { forAnyTenant: true });  // , tenantCode: this._userCntx.currentTenantCode
            if (tenantResult.output === undefined) {
                throw new Error(`Cannot read the current tenant record [${this._userCntx.currentTenantCode}].`);
            }
            let subxId = (_a = tenantResult.output.currentSubscription) === null || _a === void 0 ? void 0 : _a.id; // This assertion operator is legit cuz we're pulling from a db read.
            return subxId;
        });
    }
    searchForExistingEnterprise(enterprise_code) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let existings = yield this._codiacApi.Enterprise.readMany({ code: { $eq: enterprise_code } });
            let found = existings.find(e => e.code === enterprise_code);
            return found;
        });
    }
    buildCandidate_silently(partial) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return yield this.validatePartial(partial);
        });
    }
    buildCandidate_interactively(partial, takeDefaults) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let defaultCode = "main";
            let found = {};
            //default to main if no code provided vial CLI flag
            partial.enterprise_code = partial.enterprise_code || defaultCode;
            do {
                //prompt for enterprise code defaulting to the value provided via CLI flag (or the default value if non provided)
                partial.enterprise_code = (yield this._ui.prompt("name", "Enterprise name (no spaces): ", true, partial.enterprise_code));
                partial.enterprise_code = (_a = partial.enterprise_code) === null || _a === void 0 ? void 0 : _a.replace(" ", "");
                // validate that it doesnt already exist
                found = yield this.searchForExistingEnterprise(partial.enterprise_code);
                if (found !== undefined) {
                    this._ui.userMessage(`${this._styler.colorWarning("INVALID: ")} An enterprise with that name already exists for this tenant.`);
                }
            } while (found !== undefined);
            return yield this.validatePartial(partial);
        });
    }
    executeTask(candidate) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let final_candidate = Object.assign({ code: candidate.enterprise_code, subscription: yield this.getMyTenantSubscriptionId(), assets: [], products: [], domains: [] }, this.createAuditable());
            this._ui.startSpinner(`Creating new enterprise [${final_candidate.code}]...`);
            // let result = await this.relayClient.enterpriseCreate(partial.code!);
            let result = yield this._codiacApi.Enterprise.tryCreate(final_candidate);
            this._ui.stopSpinner("");
            if (result.error) {
                this.logger.error(`Error creating enterprise: ${result.message || ""}; ${result.error.message}`, result.error);
                this._ui.userMessage(`Error creating enterprise: ${result.message || ""}; ${result.error.message}`);
            }
            else if (!result.success) {
                this.logger.notice(`Enterprise creation failed without error.  ${result.message}`);
                this._ui.userMessage(`Enterprise creation failed without error.  ${result.message}`);
            }
            else if (result.output) {
                let saved = result.output;
                this.logger.notice(`${this._styler.colorGood("Success!")} Enterprise [${this._styler.hilite(saved.code)}] created for tenannt [${this._userCntx.currentTenantCode}]`);
                this._ui.userMessage(`${this._styler.colorGood("Success!")} Enterprise [${this._styler.hilite(saved.code)}] created for tenannt [${this._userCntx.currentTenantCode}]`);
            }
        });
    }
}
exports.default = EnterpriseCreate;
EnterpriseCreate.description = 'Creates a new enterprise under the current tenant.';
EnterpriseCreate.args = {
    code: core_1.Args.string({ required: false, description: 'The unique human-readable identitifer to use for the enterprise (must be alphanunmeric with no spaces).' })
};
EnterpriseCreate.examples = [
    { description: "Create enterprise interactivley.", command: "cod enterprise create" },
    { description: "Create enterprise interactivley with enterprise name.", command: "cod enterprise create my-enterprise-code" },
    { description: "Create enterprise silently.", command: "cod enterprise create my-enterprise-code --silent" },
];
EnterpriseCreate.flags = Object.assign(Object.assign({}, cli_common_1.commandBase.globalFlags), { help: core_1.Flags.help({ char: 'h' }), 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.' }), 
    //Not sure what to do with this one yet
    "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)." }) });
//# sourceMappingURL=create.js.map