"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateDeploymentForBuildFile = updateDeploymentForBuildFile;
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const add_1 = require("./add");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const chalk_1 = __importDefault(require("chalk"));
exports.command = `update <${constants_1.CommandArgId}>`;
exports.describe =
    'Update mobile build file associated with an environment or add new association';
exports.builder = (yargs) => {
    (0, add_1.addEnvironmentBuildFilesOptions)(yargs)
        .positional(constants_1.CommandArgId, {
        describe: 'ID of environment to update mobile build file association',
        type: 'string',
    })
        .demandOption(constants_1.CommandArgApplicationId)
        .demandOption(constants_1.CommandArgMobileBuildFileId);
};
exports.handler = (0, cliUtil_1.failWrapper)(updateOrCreateDeployment);
async function updateOrCreateDeployment(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const applicationId = parsed[constants_1.CommandArgApplicationId];
    const environmentId = parsed[constants_1.CommandArgId];
    const buildFileId = parsed[constants_1.CommandArgMobileBuildFileId];
    try {
        await apiClient.getApplication(applicationId);
        const buildFile = await apiClient.getMobileAppFile(buildFileId);
        const environment = await apiClient.getEnvironment(environmentId);
        await updateDeploymentForBuildFile(apiClient, environment, applicationId, buildFile);
        return 'done';
    }
    catch (error) {
        throw new Error(`Error updating build file for environment ${parsed.id}: ${error}`);
    }
}
async function updateDeploymentForBuildFile(apiClient, environment, applicationId, newBuildFile) {
    const deploymentEntities = await apiClient.queryDeploymentEntities(environment.organization_id ?? '', environment.id, applicationId, 1000);
    const candidatesForUpdate = deploymentEntities?.deployments
        ?.filter((deployment) => !!deployment.mobile_app_file_id)
        ?.filter(async (deployment) => {
        const buildFile = await apiClient.getMobileAppFile(deployment.mobile_app_file_id);
        return (deployment.deployment_type ===
            mablApi_1.Deployment.DeploymentTypeEnum.MobileApplication &&
            buildFile.platform === newBuildFile.platform);
    }) ?? [];
    if (candidatesForUpdate?.length === 0) {
        await (0, add_1.createDeploymentForBuildFile)(apiClient, environment, applicationId, newBuildFile.id);
        return;
    }
    else if (candidatesForUpdate?.length > 1) {
        throw new Error('Multiple deployments with the same mobile platform found. Please remove duplicates or use mabl UI to change the build file association.');
    }
    try {
        const existingDeployment = candidatesForUpdate[0];
        existingDeployment.mobile_app_file_id = newBuildFile.id;
        await apiClient.updateDeployment(existingDeployment.id, existingDeployment);
        loggingProvider_1.logger.info(chalk_1.default.white(`Updated ${newBuildFile.platform} build file associated with environment ${environment.id} and application ${applicationId} to ${newBuildFile.id} `));
    }
    catch (error) {
        loggingProvider_1.logger.error(error);
        const reRunCommandString = `mabl environments build-files update ${environment.id} --applicationId ${applicationId} --build-file-id ${newBuildFile.id}`;
        loggingProvider_1.logger.info(chalk_1.default.white(`Associating build file with environment failed. You can reattempt this association by running ${chalk_1.default.bold(reRunCommandString)}`));
    }
}
