"use strict";
/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsupportedWindowFunctionDetector = void 0;
const rule_index_1 = require("../rule_index");
const range_utils_1 = require("../range_utils");
const UNSUPPORTED_WINDOW_FUNCTIONS = new Set([
    'rank',
    'dense_rank',
    'percent_rank',
    'cume_dist',
    'nth',
    'ntile',
    'first',
    'last',
]);
const WINDOW_COMMAND_RULES = ['eventstatsCommand', 'streamstatsCommand'];
function collectWindowFunctionNames(aggTerm, ruleNameToIndex) {
    const results = [];
    const windowFns = (0, rule_index_1.findAllDescendantsByRule)(aggTerm, ruleNameToIndex, 'windowFunction');
    for (const windowFn of windowFns) {
        const nameNode = (0, rule_index_1.findChildByRule)(windowFn, ruleNameToIndex, 'windowFunctionName');
        if (!nameNode) {
            continue;
        }
        const scalarNode = (0, rule_index_1.findChildByRule)(nameNode, ruleNameToIndex, 'scalarWindowFunctionName');
        const targetNode = scalarNode ?? nameNode;
        const text = (0, rule_index_1.getTokenText)(targetNode).toLowerCase();
        if (text) {
            results.push({ name: text, node: targetNode });
        }
    }
    return results;
}
const unsupportedWindowFunctionDetector = (tree, config, _context, ruleNameToIndex) => {
    const diagnostics = [];
    const commands = [];
    for (const ruleName of WINDOW_COMMAND_RULES) {
        commands.push(...(0, rule_index_1.findAllDescendantsByRule)(tree, ruleNameToIndex, ruleName));
    }
    for (const command of commands) {
        const fns = collectWindowFunctionNames(command, ruleNameToIndex);
        for (const fn of fns) {
            if (UNSUPPORTED_WINDOW_FUNCTIONS.has(fn.name)) {
                diagnostics.push({
                    ruleId: config.id,
                    severity: config.severity,
                    message: config.message,
                    range: (0, range_utils_1.rangeFromContext)(fn.node),
                    docUrl: config.docUrl,
                    hoverFacts: { windowFunction: fn.name },
                });
            }
        }
    }
    return diagnostics;
};
exports.unsupportedWindowFunctionDetector = unsupportedWindowFunctionDetector;
//# sourceMappingURL=unsupported_window_function.js.map