import Includes from "../../Types/BaseDatabase/Includes";
import { DashboardVariableType, } from "../../Types/Dashboard/DashboardVariable";
import DashboardVariableInterpolation from "./VariableInterpolation";
/*
 * Applies dashboard variables to a Postgres model query at render time.
 *
 * Companion to `DashboardVariableInterpolation`, which targets OTel
 * attribute filters used by metric/log widgets. Resource list widgets
 * (Host, Kubernetes resources, Docker resources) query the model store
 * by column instead, so this helper translates the variable's bound
 * OTel attribute key into the matching column name before writing the
 * predicate. An empty/unset selection removes any prior filter on that
 * column so the list falls back to its widget-default view.
 */
export default class DashboardModelQueryInterpolation {
    static applyToQuery(query, variables, attributeToColumn) {
        if (!variables || variables.length === 0) {
            return query;
        }
        const mappedAttributeKeys = Object.keys(attributeToColumn);
        if (mappedAttributeKeys.length === 0) {
            return query;
        }
        const relevantVariables = variables.filter((v) => {
            return (v.type === DashboardVariableType.TelemetryAttribute &&
                Boolean(v.attributeKey) &&
                mappedAttributeKeys.includes(v.attributeKey));
        });
        if (relevantVariables.length === 0) {
            return query;
        }
        let next = query;
        let changed = false;
        for (const variable of relevantVariables) {
            const column = attributeToColumn[variable.attributeKey];
            const resolved = DashboardVariableInterpolation.resolveValue(variable);
            if (!resolved) {
                if (column in next) {
                    if (!changed) {
                        next = Object.assign({}, query);
                        changed = true;
                    }
                    delete next[column];
                }
                continue;
            }
            if (resolved.multi && resolved.multi.length > 0) {
                if (!changed) {
                    next = Object.assign({}, query);
                    changed = true;
                }
                next[column] = new Includes(resolved.multi);
                continue;
            }
            if (resolved.scalar !== undefined && next[column] !== resolved.scalar) {
                if (!changed) {
                    next = Object.assign({}, query);
                    changed = true;
                }
                next[column] = resolved.scalar;
            }
        }
        return changed ? next : query;
    }
}
//# sourceMappingURL=ModelQueryVariableInterpolation.js.map