"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDescribeDescriptions = getDescribeDescriptions;
exports.getWorkspaceId = getWorkspaceId;
exports.getWorkspaceIdFromAppOrEnv = getWorkspaceIdFromAppOrEnv;
exports.validateArrayInputs = validateArrayInputs;
exports.validateValuePairInputs = validateValuePairInputs;
exports.parseColonJoinedVariablePair = parseColonJoinedVariablePair;
exports.getCredentialType = getCredentialType;
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const chalk_1 = __importDefault(require("chalk"));
const cliConfigProvider_1 = require("@mablhq-internal/runtime/providers/cliConfigProvider");
const constants_1 = require("@mablhq-internal/runtime/core/constants");
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const pluralize_1 = __importDefault(require("pluralize"));
function getDescribeDescriptions(entityName) {
    return `Describe a specific ${entityName}`;
}
async function getWorkspaceId(parsed) {
    const workspaceId = parsed[constants_1.CommandArgWorkspaceId];
    if (workspaceId) {
        return workspaceId;
    }
    const configuredWorkspace = await cliConfigProvider_1.CliConfigProvider.getWorkspace();
    if (configuredWorkspace?.id) {
        return configuredWorkspace.id;
    }
    throw new Error('Please specify a workspace ID (--workspace-id) or configure a default in the CLI (mabl config set workspace <id>)');
}
async function getWorkspaceIdFromAppOrEnv(apiClient, applicationId, environmentId) {
    if (applicationId) {
        const application = await apiClient.getApplication(applicationId);
        return application.organization_id;
    }
    else if (environmentId) {
        const environment = await apiClient.getEnvironment(environmentId);
        return environment.organization_id;
    }
    throw new Error('Either Application or Environment ID must be provided');
}
function validateArrayInputs(possibleInput, errorMessage) {
    if (possibleInput !== undefined) {
        const labels = possibleInput;
        if (labels.some((label) => /[,|;]/.test(label))) {
            throw new Error(errorMessage);
        }
    }
}
function validateValuePairInputs(inputName, inputs) {
    if (inputs) {
        const missingColonInputs = inputs
            .map((input) => input.trim())
            .filter((input) => !/^([^:]+)?:(.+)?$/m.test(input));
        if (missingColonInputs.length > 0) {
            throw new Error(`${inputName} ${(0, pluralize_1.default)('value', missingColonInputs.length)} must separate kev/value with a colon ':', [${missingColonInputs.join(',')}]`);
        }
        const missingNameInputs = inputs
            .map((input) => input.replace(/^[ ]+/, ''))
            .filter((input) => !/^([^:]+):(.+)?$/m.test(input));
        if (missingNameInputs.length > 0) {
            throw new Error(`${inputName} ${(0, pluralize_1.default)('name', missingNameInputs.length)} cannot be blank [${missingNameInputs.join(',')}]`);
        }
        const illegalCharacterHeaders = inputs.filter((input) => /[\n\r]/m.test(input));
        if (illegalCharacterHeaders.length > 0) {
            const escapedHeaders = illegalCharacterHeaders.map((input) => input.replace('\n', '\\n').replace('\r', '\\r'));
            throw new Error(`${inputName} shouldn't contain carriage return or line feed characters [${escapedHeaders.join(',')}]`);
        }
        const wrappingWhitespace = inputs.filter((header) => !/^([^\s:]{1,2}|[^\s:][^:]+[^\s:]):([^\s:]{1,2}|[^\s:][^:]+[^\s:])?$/m.test(header));
        if (wrappingWhitespace.length > 0) {
            const cleanFunction = (header) => {
                const { name, value } = parseColonJoinedVariablePair(header);
                return [name, value].map((part) => part.trim()).join(':');
            };
            const cleaned = inputs.map(cleanFunction);
            const cleanedAffectedHeaders = wrappingWhitespace.map(cleanFunction);
            loggingProvider_1.logger.info(chalk_1.default.yellow.bold(`${inputName} wrapping whitespace detected. Whitespace has been trimmed to [`) +
                chalk_1.default.white.bold(cleanedAffectedHeaders.join(',')) +
                chalk_1.default.yellow.bold(']'));
            return cleaned;
        }
    }
    return inputs;
}
function parseColonJoinedVariablePair(input) {
    const name = input.substring(0, input.indexOf(':'));
    const value = input.substring(input.indexOf(':') + 1);
    return { name, value };
}
function getCredentialType(credential) {
    if (credential.cloud_only) {
        return credential.type === mablApi_1.Credentials.TypeEnum.Basic
            ? 'Cloud'
            : 'Cloud with MFA';
    }
    return credential.type === mablApi_1.Credentials.TypeEnum.Basic
        ? 'Basic'
        : 'Basic with MFA';
}
