"use strict";
/*
 * @adonisjs/env
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.oneOf = void 0;
const utils_1 = require("@poppinss/utils");
const helpers_1 = require("./helpers");
/**
 * Validates the number to be present in the user defined choices.
 *
 * The incoming value will be casted as follows:
 *
 * - "0", 0, "false", false will be casted to false
 * - "1", 1, "true", true will be casted to true
 * - string representation of a number will be casted to a number
 */
function ensureOneOf(choices, key, value, message) {
    if (helpers_1.BOOLEAN_NEGATIVES.includes(value)) {
        value = false;
    }
    else if (helpers_1.BOOLEAN_POSITIVES.includes(value)) {
        value = true;
    }
    else {
        const toNumber = Number(value);
        if (!isNaN(toNumber)) {
            value = toNumber;
        }
    }
    /**
     * If choices includes the value, then return the casted
     * value
     */
    if (choices.includes(value)) {
        return value;
    }
    /**
     * Otherwise raise exception
     */
    throw new utils_1.Exception(message ||
        `Value for environment variable "${key}" must be one of "${choices.join(',')}", instead received "${value}"`, 500, 'E_INVALID_ENV_VALUE');
}
/**
 * Enforces value to be one of the defined choices
 */
function oneOf(choices, options) {
    return function validate(key, value) {
        (0, helpers_1.ensureValue)(key, value, options?.message);
        return ensureOneOf(choices, key, value, options?.message);
    };
}
exports.oneOf = oneOf;
/**
 * Similar to oneOf, but also allows optional properties
 */
oneOf.optional = function optionalBoolean(choices, options) {
    return function validate(key, value) {
        if (!value) {
            return undefined;
        }
        return ensureOneOf(choices, key, value, options?.message);
    };
};
