"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("../../constants");
const awaitDeploymentCompletion_1 = require("./awaitDeploymentCompletion");
const create_1 = require("./create");
exports.command = 'watch <id>';
exports.describe =
    'Watch a mabl deployment event until completion, with results';
exports.builder = (yargs) => {
    yargs
        .option(constants_1.CommandArgFastFailure, {
        describe: `Exit on first failed test`,
        type: 'boolean',
        default: false,
    })
        .option(constants_1.CommandArgSilent, {
        describe: "Don't output runtime status",
        type: 'boolean',
        default: false,
    })
        .implies(constants_1.CommandArgOutput, constants_1.CommandArgSilent)
        .option(constants_1.CommandArgOutput, {
        alias: constants_1.CommandArgAliases.OutputType,
        describe: 'Specify final result output format. Implies: --silent',
        choices: constants_1.DefaultOutputFormatChoices,
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(getWatch);
async function getWatch(parsed) {
    const deploymentId = parsed.id;
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const deploymentEvent = await apiClient.getDeploymentEvent(deploymentId);
    const outputWebappLink = (0, create_1.getDeploymentEventWebappUrl)(deploymentEvent);
    const waiter = new awaitDeploymentCompletion_1.AwaitDeploymentCompletion(apiClient, parsed['fast-failure'], parsed.silent);
    const pollingResult = await waiter.awaitCompletion(deploymentEvent.id);
    const isSuccess = pollingResult?.newEntity?.event_status?.succeeded || false;
    if (!isSuccess) {
        process.exit(1);
    }
    return outputWebappLink;
}
