"use strict";
/*
 * @adonisjs/validator
 *
 * (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.requiredIfExists = void 0;
const helpers_1 = require("../../Validator/helpers");
const RULE_NAME = 'requiredIfExists';
const DEFAULT_MESSAGE = 'requiredIfExists validation failed';
/**
 * Ensure the value exists. `null`, `undefined` and `empty string`
 * fails the validation
 */
exports.requiredIfExists = {
    compile: (0, helpers_1.wrapCompile)(RULE_NAME, [], ([field]) => {
        if (!field) {
            throw new Error(`"${RULE_NAME}": expects a "field"`);
        }
        return {
            allowUndefineds: true,
            compiledOptions: {
                field,
            },
        };
    }),
    validate(value, compiledOptions, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
        const otherFieldExists = (0, helpers_1.exists)((0, helpers_1.getFieldValue)(compiledOptions.field, root, tip));
        if (otherFieldExists && !(0, helpers_1.exists)(value)) {
            errorReporter.report(pointer, RULE_NAME, DEFAULT_MESSAGE, arrayExpressionPointer, {
                otherField: compiledOptions.field,
            });
        }
    },
};
