"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.validate = exports.compile = void 0;
const luxon_1 = require("luxon");
const toLuxon_1 = require("./toLuxon");
const helpers_1 = require("../../../Validator/helpers");
/**
 * Returns a luxon date time instance based upon the unit, duration and operator
 */
function compareDateTime(lhs, rhs, operator) {
    switch (operator) {
        case '>':
            return lhs > rhs;
        case '<':
            return lhs < rhs;
        case '>=':
            return lhs >= rhs;
        case '<=':
            return lhs <= rhs;
    }
}
/**
 * Compiles a date field comparison rule
 */
function compile(ruleName, operator, [field], rulesTree) {
    if (!field) {
        throw new Error(`${ruleName}: expects a comparison "field"`);
    }
    return {
        compiledOptions: {
            operator,
            field,
            format: rulesTree.date?.format,
        },
    };
}
exports.compile = compile;
/**
 * Validates date field comparison rule
 */
function validate(ruleName, errorMessage, value, { field, operator, format }, { root, tip, errorReporter, pointer, arrayExpressionPointer }) {
    /**
     * Skip when value is not a date time instance. One must use date schema
     * type
     */
    if (luxon_1.DateTime.isDateTime(value) === false) {
        return;
    }
    const comparisonValue = (0, toLuxon_1.toLuxon)((0, helpers_1.getFieldValue)(field, root, tip), format);
    /**
     * Raise error when comparison field is not a valid date
     */
    if (!comparisonValue || !comparisonValue.isValid) {
        errorReporter.report(pointer, ruleName, errorMessage, arrayExpressionPointer, {
            otherField: field,
            otherFieldValue: comparisonValue,
        });
        return;
    }
    if (!compareDateTime(value, comparisonValue, operator)) {
        errorReporter.report(pointer, ruleName, errorMessage, arrayExpressionPointer, {
            otherField: field,
            otherFieldValue: comparisonValue,
        });
    }
}
exports.validate = validate;
