"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateOptions = exports.validationRules = exports.wrapCheckType = exports.requiresOneOf = exports.requires = exports.incompatibleWith = exports.deprecatedFunction = void 0;
const checkTypes = require("check-types");
const logger_1 = __importStar(require("../logger"));
const underscore_1 = require("underscore");
const deprecatedFunction = (_) => (_, property) => {
    logger_1.default.warn(`${property} is deprecated and no longer has any effect`);
    return true;
};
exports.deprecatedFunction = deprecatedFunction;
const incompatibleWith = (keys) => (options) => (_, property) => {
    const incompatibilities = underscore_1.pick(options, keys);
    if (Object.keys(incompatibilities).length > 0) {
        logger_1.logErrorAndThrow(`${property} is incompatible with the following properties: ${keys.join(',')}`);
        return false;
    }
    return true;
};
exports.incompatibleWith = incompatibleWith;
const requires = (keys) => (options) => (_, property) => {
    const required = underscore_1.pick(options, keys);
    if (keys.length !== Object.keys(required).length) {
        logger_1.logErrorAndThrow(`${property} requires the following properties: ${keys.join(',')}`);
        return false;
    }
    return true;
};
exports.requires = requires;
const requiresOneOf = (keys) => (options) => (_, property) => {
    const required = underscore_1.pick(options, keys);
    if (Object.keys(required).length === 0) {
        logger_1.logErrorAndThrow(`${property} requires one of the following properties: ${keys.join(',')}`);
        return false;
    }
    return true;
};
exports.requiresOneOf = requiresOneOf;
const wrapCheckType = (fn) => (_) => fn;
exports.wrapCheckType = wrapCheckType;
const LogLevels = ['debug', 'error', 'info', 'trace', 'warn'];
const logLevelValidator = (_) => (l) => {
    if (LogLevels.includes(l.toLowerCase())) {
        l = l.toLowerCase();
    }
    else {
        throw new Error(`The logLevel '${l}' is not a valid logLevel. The valid options are: ${LogLevels.join(', ')}`);
    }
    return true;
};
const consumerVersionSelectorValidator = (options) => (l) => {
    if (options.consumerVersionSelectors &&
        Array.isArray(options.consumerVersionSelectors)) {
        const PROPS = [
            'tag',
            'latest',
            'consumer',
            'deployedOrReleased',
            'deployed',
            'released',
            'environment',
            'fallbackTag',
            'branch',
            'mainBranch',
            'matchingBranch',
        ];
        options.consumerVersionSelectors.forEach((selector) => {
            if (selector.tag === 'latest') {
                logger_1.default.warn("Using the tag 'latest' is not recommended and probably does not do what you intended.");
                logger_1.default.warn('    See https://docs.pact.io/pact_broker/tags/#latest-pacts');
                logger_1.default.warn('    If you need to specify latest, try:');
                logger_1.default.warn('       consumerVersionSelectors: [{ lastest: true }]');
            }
            Object.keys(selector).forEach((key) => {
                if (!PROPS.includes(key)) {
                    logger_1.default.warn(`The consumer version selector '${key}' is unknown but will be sent through to the validation. Allowed properties are ${PROPS.join(', ')})`);
                }
            });
        });
    }
    return true;
};
const consumerVersionTagsValidator = (options) => (l) => {
    if (options.consumerVersionTags) {
        if (!checkTypes.string(options.consumerVersionTags) &&
            !checkTypes.array.of.string(options.consumerVersionTags)) {
            throw new Error('consumerVersionTags should be a string or an array of strings');
        }
        if (options.consumerVersionTags.includes('latest')) {
            logger_1.default.warn("Using the tag 'latest' is not recommended and probably does not do what you intended.");
            logger_1.default.warn('    See https://docs.pact.io/pact_broker/tags/#latest-pacts');
            logger_1.default.warn('    If you need to specify latest, try:');
            logger_1.default.warn('       consumerVersionSelectors: [{ lastest: true }]');
        }
    }
    return true;
};
exports.validationRules = {
    providerBaseUrl: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    buildUrl: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    consumerVersionSelectors: [consumerVersionSelectorValidator],
    consumerVersionTags: [consumerVersionTagsValidator],
    customProviderHeaders: [exports.wrapCheckType(checkTypes.assert.nonEmptyObject)],
    disableSslVerification: [exports.wrapCheckType(checkTypes.assert.boolean)],
    enablePending: [exports.wrapCheckType(checkTypes.assert.boolean)],
    format: [exports.deprecatedFunction],
    includeWipPactsSince: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    provider: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    pactUrls: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    pactBrokerUrl: [
        exports.wrapCheckType(checkTypes.assert.nonEmptyString),
        exports.requires(['provider']),
        exports.requiresOneOf([
            'pactUrls',
            'consumerVersionSelectors',
            'consumerVersionTags',
        ]),
    ],
    pactBrokerUsername: [
        exports.wrapCheckType(checkTypes.assert.nonEmptyString),
        exports.incompatibleWith(['pactBrokerToken']),
        exports.requires(['pactBrokerPassword']),
    ],
    pactBrokerPassword: [
        exports.wrapCheckType(checkTypes.assert.nonEmptyString),
        exports.incompatibleWith(['pactBrokerToken']),
        exports.requires(['pactBrokerUsername']),
    ],
    pactBrokerToken: [
        exports.wrapCheckType(checkTypes.assert.nonEmptyString),
        exports.incompatibleWith(['pactBrokerUsername', 'pactBrokerPassword']),
    ],
    providerVersionTags: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    providerBranch: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    providerStatesSetupUrl: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    providerStatesSetupTeardown: [exports.wrapCheckType(checkTypes.assert.boolean)],
    providerStatesSetupBody: [exports.wrapCheckType(checkTypes.assert.boolean)],
    publishVerificationResult: [
        exports.wrapCheckType(checkTypes.assert.boolean),
        exports.requires(['providerVersion']),
    ],
    providerVersion: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
    timeout: [exports.wrapCheckType(checkTypes.assert.positive)],
    logLevel: [logLevelValidator],
    out: [exports.deprecatedFunction],
    verbose: [exports.deprecatedFunction],
    monkeypatch: [exports.deprecatedFunction],
    logDir: [exports.deprecatedFunction],
    consumerFilters: [exports.wrapCheckType(checkTypes.assert.nonEmptyString)],
};
const validateOptions = (options) => {
    Object.keys(options).concat('providerBaseUrl').map((k) => {
        const rules = exports.validationRules[k];
        if (Array.isArray(options[k])) {
            options[k].map((item) => {
                rules.map((rule) => {
                    rule(options)(item, k);
                });
            });
        }
        else {
            rules.map((rule) => {
                rule(options)(options[k], k);
            });
        }
    });
    return options;
};
exports.validateOptions = validateOptions;
//# sourceMappingURL=validateOptions.js.map