"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const util_1 = require("../../commandUtil/util");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const branches_1 = require("@mablhq-internal/runtime/util/branches/branches");
const describe_1 = require("../../commandUtil/describe");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const CommandArgFrom = 'from';
const CommandArgTo = 'to';
exports.command = 'merge';
exports.describe = 'Merge mabl branches';
exports.builder = (yargs) => {
    yargs
        .option(CommandArgFrom, {
        alias: constants_2.CommandArgAliases.BranchFrom,
        describe: 'Name of the mabl branch to merge from',
        type: 'string',
        demand: `a mabl from branch [--${CommandArgFrom}] is required`,
        nargs: 1,
    })
        .option(CommandArgTo, {
        alias: constants_2.CommandArgAliases.BranchTo,
        describe: 'Name of the mabl branch to merge to',
        type: 'string',
        default: 'master',
        nargs: 1,
    })
        .option(constants_2.CommandArgOutput, {
        alias: constants_2.CommandArgAliases.OutputType,
        describe: 'Specify an output type for the branch data',
        choices: constants_2.DefaultOutputFormatChoices,
    })
        .option(constants_1.CommandArgWorkspaceId, {
        alias: constants_2.CommandArgAliases.WorkspaceId,
        describe: 'The workspace ID to create a new branch',
        nargs: 1,
        type: 'string',
    })
        .check((argv) => {
        const fromBranchName = argv[CommandArgFrom];
        if (!(0, branches_1.isValidMablBranchName)(fromBranchName)) {
            throw new Error(`[${fromBranchName}] is not a valid mabl branch name. Please specify a valid name`);
        }
        return true;
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(mergeBranch);
async function mergeBranch(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const fromBranchName = parsed.from;
    const toBranchName = parsed.to;
    const branch = await apiClient.mergeBranch(workspaceId, fromBranchName, toBranchName);
    (0, describe_1.outputEntity)(branch, parsed.output);
    return branch.id;
}
