"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 ApiError_1 = require("@mablhq-internal/runtime/api/ApiError");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
exports.command = 'create <name>';
exports.describe = 'Create a new mabl branch';
exports.builder = (yargs) => {
    yargs
        .positional(constants_2.CommandArgName, {
        describe: 'Name of the mabl branch to create',
        nargs: 1,
        type: 'string',
        demand: 'branch name is required',
    })
        .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 branchName = argv[constants_2.CommandArgName];
        if (!(0, branches_1.isValidMablBranchName)(branchName)) {
            throw new Error(`[${branchName}] is not a valid mabl branch name. Please specify a valid name`);
        }
        return true;
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(createBranch);
async function createBranch(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const branchName = parsed.name;
    loggingProvider_1.logger.info(`Creating Branch [${branchName}]`);
    try {
        const branch = await apiClient.createBranch(workspaceId, branchName);
        (0, describe_1.outputEntity)(branch, parsed.output);
        return branch.id;
    }
    catch (creationError) {
        if (creationError instanceof ApiError_1.ApiError && creationError.statusCode === 400) {
            throw new Error(`mabl branch with [${branchName}] may already exist in workspace [${workspaceId}]`);
        }
        throw creationError;
    }
}
