"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addEnvironmentUrlOptions = addEnvironmentUrlOptions;
exports.createDeploymentForUrl = createDeploymentForUrl;
const constants_1 = require("../../../constants");
const constants_2 = require("@mablhq-internal/runtime/core/constants");
const util_1 = require("../../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const chalk_1 = __importDefault(require("chalk"));
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
exports.command = `add <${constants_2.CommandArgId}>`;
exports.describe = 'Associate URLs with an environment';
exports.builder = (yargs) => {
    addEnvironmentUrlOptions(yargs)
        .positional(constants_2.CommandArgId, {
        describe: 'Id of environment to add URL associations to',
        type: 'string',
    })
        .demandOption(constants_2.CommandArgApplicationId);
};
exports.handler = (0, cliUtil_1.failWrapper)(createDeployments);
function addEnvironmentUrlOptions(yargs) {
    return yargs
        .option(constants_2.CommandArgApplicationId, {
        describe: 'id of application to associate with this environment',
        nargs: 1,
        type: 'string',
    })
        .option(constants_1.CommandArgUrlApp, {
        describe: 'web application URLs to associate with the application-environment pair',
        type: 'array',
    })
        .option(constants_2.CommandArgUrlApi, {
        describe: 'API URLs to associate with the application-environment pair',
        type: 'array',
    })
        .check((argv) => {
        const applicationId = argv[constants_2.CommandArgApplicationId];
        const appUrls = argv[constants_1.CommandArgUrlApp];
        const apiUrls = argv[constants_2.CommandArgUrlApi];
        if (applicationId &&
            (!appUrls || appUrls.length === 0) &&
            (!apiUrls || apiUrls.length === 0)) {
            throw new Error(`Must specify at least one url if adding an application association to the environment`);
        }
        if (appUrls) {
            (0, util_1.validateArrayInputs)(appUrls, 'Urls must be SPACE delimited, e.g. "--api-urls=http://mabl.com http://api.mabl.com');
        }
        if (apiUrls) {
            (0, util_1.validateArrayInputs)(apiUrls, 'Urls must be SPACE delimited, e.g. "--api-urls=http://mabl.com http://api.mabl.com');
        }
        return true;
    });
}
async function createDeploymentForUrl(apiClient, environment, applicationId, url, type) {
    try {
        let deployment = {
            organization_id: environment.organization_id,
            environment_id: environment.id,
            application_id: applicationId,
            uri: url,
            deployment_type: type,
        };
        deployment = await apiClient.createDeployment(deployment);
        loggingProvider_1.logger.info(chalk_1.default.white(`Associated ${url} with environment ${environment.id}`));
    }
    catch (error) {
        loggingProvider_1.logger.error(error);
        const reRunCommandString = `mabl environments add-url ${environment.id} --applicationId ${applicationId} --${type === mablApi_1.Deployment.DeploymentTypeEnum.Api ? 'api-url' : 'app-url'} ${url}`;
        loggingProvider_1.logger.info(chalk_1.default.white(`Associating url with environment failed.  You can reattempt this association by running ${chalk_1.default.bold(reRunCommandString)}`));
    }
}
async function createDeployments(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const applicationId = parsed[constants_2.CommandArgApplicationId];
    try {
        const environment = await apiClient.getEnvironment(parsed.id);
        const createDeploymentsPromises = (parsed[constants_1.CommandArgUrlApp] || [])
            .map(async (url) => createDeploymentForUrl(apiClient, environment, applicationId, url, mablApi_1.Deployment.DeploymentTypeEnum.WebApplication))
            .concat((parsed[constants_2.CommandArgUrlApi] || []).map(async (url) => createDeploymentForUrl(apiClient, environment, applicationId, url, mablApi_1.Deployment.DeploymentTypeEnum.Api)));
        await Promise.all(createDeploymentsPromises);
        return 'done';
    }
    catch (error) {
        throw new Error(`Error adding urls for environment ${parsed.id}: ${error}`);
    }
}
