"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
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 constants_1 = require("@mablhq-internal/runtime/core/constants");
const constants_2 = require("../../constants");
const chalk_1 = __importDefault(require("chalk"));
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
exports.command = 'delete <identifier>';
exports.describe = 'Delete a mabl branch by id or name';
exports.builder = (yargs) => {
    yargs
        .positional('identifier', {
        describe: 'The branch ID or NAME to delete',
        type: 'string',
        nargs: 1,
        demand: 'Branch identifier is required',
    })
        .option(constants_2.CommandArgName, {
        alias: constants_2.CommandArgAliases.Name,
        describe: 'Use identifier as branch name',
        type: 'boolean',
        default: false,
    })
        .option(constants_1.CommandArgWorkspaceId, {
        alias: constants_2.CommandArgAliases.WorkspaceId,
        describe: 'The workspace ID to delete a branch by name',
        nargs: 1,
        type: 'string',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(deleteBranch);
async function deleteBranch(parsed) {
    try {
        const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
        const branchIdentifier = parsed.identifier;
        const lookupByName = parsed.name;
        let branchId;
        let branchLabel;
        if (lookupByName) {
            if (!(0, branches_1.isValidMablBranchName)(branchIdentifier)) {
                throw new Error(`[${branchIdentifier}] is not a valid mabl branch name. Please specify a valid name`);
            }
            const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
            const branch = await apiClient.getBranchByName(workspaceId, branchIdentifier);
            branchId = branch.id ?? branchIdentifier;
            branchLabel = branch.name ?? branchIdentifier;
        }
        else {
            branchId = branchIdentifier;
            branchLabel = branchIdentifier;
        }
        await apiClient.deleteBranch(branchId);
        loggingProvider_1.logger.info(chalk_1.default.green(`Branch ${chalk_1.default.bold(branchLabel)} DELETED`));
        return branchId;
    }
    catch (error) {
        throw new Error(`Error deleting branch: ${error}`);
    }
}
