"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const authenticationProvider_1 = require("@mablhq-internal/runtime/providers/authenticationProvider");
const constants_1 = require("../../constants");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cliConfigProvider_1 = require("@mablhq-internal/runtime/providers/cliConfigProvider");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
exports.command = `activate-key <${constants_1.CommandArgApiKey}>`;
exports.describe = 'Activate auth by api key';
exports.builder = {};
exports.builder = (yargs) => {
    yargs
        .positional(constants_1.CommandArgApiKey, {
        describe: 'API key (escape leading dashes with "\\" (e.g. "\\-yourKey")',
        type: 'string',
        nargs: 1,
        demand: 'API key argument required',
    })
        .option('skip-workspace', {
        describe: 'Set to skip validating and setting the workspace',
        default: false,
        hidden: true,
        type: 'boolean',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(activateApiKey);
async function activateApiKey(parsed) {
    const auth = new authenticationProvider_1.AuthenticationProvider();
    const apiKey = parsed['api-key'];
    const cleanApiKey = apiKey.replace(/^\\+/, '');
    const mablApi = await mablApiClientFactory_1.MablApiClientFactory.createApiClientFromApiKey(cleanApiKey);
    const apiKeyDetails = await mablApi.getApiKeyDetails();
    if (!parsed['skip-workspace']) {
        const apiKeyWorkspace = await mablApi.getWorkspace(apiKeyDetails.workspace_id);
        await cliConfigProvider_1.CliConfigProvider.setWorkspace(apiKeyWorkspace);
    }
    return auth.activateApiKey(cleanApiKey);
}
