"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.MessagesBag = void 0;
const helpers_1 = require("@poppinss/utils/build/helpers");
/**
 * Message bag exposes the API to pull the most appropriate message for a
 * given validation failure.
 */
class MessagesBag {
    constructor(messages) {
        this.messages = messages;
        this.wildCardCallback = typeof this.messages['*'] === 'function' ? this.messages['*'] : undefined;
    }
    /**
     * Transform message by replace placeholders with runtime values
     */
    transform(message, rule, pointer, args) {
        /**
         * No interpolation required
         */
        if (!message.includes('{{')) {
            return message;
        }
        return (0, helpers_1.interpolate)(message, { rule, field: pointer, options: args || {} });
    }
    /**
     * Returns the most appropriate message for the validation failure.
     */
    get(pointer, rule, message, arrayExpressionPointer, args) {
        let validationMessage = this.messages[`${pointer}.${rule}`];
        /**
         * Fetch message for the array expression pointer if it exists
         */
        if (!validationMessage && arrayExpressionPointer) {
            validationMessage = this.messages[`${arrayExpressionPointer}.${rule}`];
        }
        /**
         * Fallback to the message for the rule
         */
        if (!validationMessage) {
            validationMessage = this.messages[rule];
        }
        /**
         * Transform and return message. The wildcard callback is invoked when custom message
         * is not defined
         */
        return validationMessage
            ? this.transform(validationMessage, rule, pointer, args)
            : this.wildCardCallback
                ? this.wildCardCallback(pointer, rule, arrayExpressionPointer, args)
                : message;
    }
}
exports.MessagesBag = MessagesBag;
