"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const codiac_domain_1 = require("@codiac.io/codiac-domain");
const command_base_exec_tenant_1 = require("../../command-base-exec-tenant");
const cloud_resource_configurator_factory_1 = require("../../uilogic/cloud-resource-configurator-factory");
const cloud_provider_contextualizer_1 = require("../../uilogic/cloud-provider-contextualizer");
const type_safety_utils_1 = require("../../uilogic/type-safety-utils");
class SecretStoreCapture extends command_base_exec_tenant_1.CommandBaseExecTenant {
    bootstrap() {
        super.bootstrap();
        cloud_provider_contextualizer_1.CloudProviderContextualizer.bootstrap(this.ioc);
    }
    captureArgs() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { flags } = yield this.parse(SecretStoreCapture);
            let partial = {};
            if (flags.name)
                partial.name = flags.name;
            if (flags.provider)
                partial.provider = type_safety_utils_1.TypeSafetyUtils.toEnum(codiac_domain_1.CloudProviderEnum, flags.provider);
            return [partial, false];
        });
    }
    buildCandidate_silently(partial, rootMap) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            throw new Error(`Silent capture not yet implemented`);
        });
    }
    buildCandidate_interactively(partial, takeDefaults, rootMap) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            cloud_resource_configurator_factory_1.SecretStoreConfiguratorFactory.bootstrap(this.ioc);
            if (partial.name) {
                let kvpStores = yield this._codiacApi.KvpStoreDef.readMany({ all: true }, { throwNotFound: false });
                let alreadyCaptured = kvpStores
                    .filter(s => [codiac_domain_1.KvpStoreTypesEnum.awsKeyVault, codiac_domain_1.KvpStoreTypesEnum.azKeyVault].map(x => x.toString()).includes(s.type))
                    .map(x => x);
                let found = alreadyCaptured.find(r => r.name === partial.name);
                if (found)
                    return found;
            }
            let factory = new cloud_resource_configurator_factory_1.SecretStoreConfiguratorFactory();
            // 1. Select a cloud resource provider
            let choices = factory.getAllProviders(this.ioc);
            partial.provider = (yield this.cspContextualizer.promptForCloudProvider(choices, partial.provider));
            // 2. Authenticate with the cloud resource provider
            let subx = (_a = partial.accountId) !== null && _a !== void 0 ? _a : partial.subscriptionId;
            let cspUser = yield this.cspContextualizer.promptForCloudProviderCreds(this.ioc, partial.provider, undefined, undefined, undefined, subx);
            if (cspUser.subscriptionId) {
                switch (partial.provider) {
                    case codiac_domain_1.CloudProviderEnum.aws:
                        partial.accountId = cspUser.subscriptionId;
                        break;
                    case codiac_domain_1.CloudProviderEnum.azure:
                        partial.subscriptionId = cspUser.subscriptionId;
                        break;
                    default:
                        partial.subscriptionId = cspUser.subscriptionId;
                        break;
                    // TODO: Add the subscriptionId property to the SecretStoreDef domain entity.
                }
            }
            // 3. Select an existing secret store
            let cfg8r = factory.create(partial.provider, this.ioc);
            let candidate = yield cfg8r.captureSecretStore(partial);
            return candidate;
        });
    }
    buildCommandString(candidate, cmd) {
        if (candidate.name)
            cmd.push("--name", candidate.name);
        if (candidate.provider)
            cmd.push("--provider", candidate.provider);
        cmd.push("--silent");
        return cmd;
    }
    executeTask(candidate) {
        var _a;
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            try {
                let minted = yield this._codiacApi.KvpStoreDef.create(candidate);
                this.logger.debug(`Successfully captured ${candidate.type} secret store [${this._styler.hilite(candidate.name)}]`, minted);
                this._ui.userMessage(`Successfully captured ${candidate.type} secret store [${this._styler.hilite(candidate.name)}]`);
            }
            catch (err) {
                this._ui.userMessage(`${this._styler.colorCritical("Error")} capturing ${candidate.type} secret store [${candidate.name}]: ${err.name} ${(_a = err.message) !== null && _a !== void 0 ? _a : err.stack}`);
                this.logger.error(err, candidate);
                throw err;
            }
        });
    }
}
exports.default = SecretStoreCapture;
SecretStoreCapture.description = 'Upserts a reference to an existing secretStore.';
SecretStoreCapture.aliases = ['secretStore'];
SecretStoreCapture.flags = {
    help: core_1.Flags.help({ char: 'h' }),
    url: core_1.Flags.string({ char: 'u', required: false, description: "The container registry url." }),
    provider: core_1.Flags.string({ char: 'p', options: Object.values(codiac_domain_1.CloudProviderEnum), required: false, description: "The cloud provider hosting the secret store." }),
    name: core_1.Flags.string({ char: 'n', required: false, description: "The resource name of the secret store within the cloud provider subscription." }),
    subscriptionId: core_1.Flags.string({ char: 's', required: false, description: "The id of the cloud provider account in which the secret store resides (in Aws, this is the 'AccountId')." }),
    location: core_1.Flags.string({ char: 'l', required: false, description: "The region or data center in which the secret store resides (use the code name, eg: in Aws use 'us-east-1', NOT 'Virginia, US')." }),
    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.' }),
};
SecretStoreCapture.args = {};
//# sourceMappingURL=capture.js.map