// (C) 2021-2026 GoodData Corporation
import { filterMeasureRef, insightFilters, insightMeasures, isAttributeFilter, isDateFilter, isMeasureValueFilter, isRankingFilter, } from "@gooddata/sdk-model";
import { getSourceMeasureFiltersForDrillDefinition, isMatchingSourceInsightFilter, resolveSourceMeasureRef, } from "../../../../_staging/drills/drillingUtils.js";
export function getIncludedSourceInsightFilters(sourceInsight, includedSourceInsightFiltersObjRefs) {
    const sourceFilters = sourceInsight
        ? insightFilters(sourceInsight).filter((filter) => isAttributeFilter(filter) ||
            isDateFilter(filter) ||
            isMeasureValueFilter(filter) ||
            isRankingFilter(filter))
        : [];
    return includedSourceFilters(sourceFilters, includedSourceInsightFiltersObjRefs);
}
export function getIncludedSourceMeasureFilters(sourceInsight, drillDefinition) {
    if (!sourceInsight) {
        return [];
    }
    const sourceMeasureFilters = getSourceMeasureFiltersForDrillDefinition(drillDefinition, insightMeasures(sourceInsight));
    return includedSourceFilters(sourceMeasureFilters, drillDefinition.includedSourceMeasureFiltersObjRefs ?? []);
}
export function getIncludedSourceFiltersForDashboard(sourceInsight, drillDefinition) {
    const sourceInsightMeasures = sourceInsight ? insightMeasures(sourceInsight) : [];
    const sourceMeasureFilters = getIncludedSourceMeasureFilters(sourceInsight, drillDefinition);
    const sourceInsightFilters = getIncludedSourceInsightFilters(sourceInsight, drillDefinition.includedSourceInsightFiltersObjRefs ?? [])
        .filter((filter) => {
        return isAttributeFilter(filter) || isDateFilter(filter) || isMeasureValueFilter(filter);
    })
        .flatMap((filter) => normalizeSourceFilterForDashboard(filter, sourceInsightMeasures));
    // Keep the same precedence as drill-to-insight: measure filters win over source insight filters.
    return [...sourceMeasureFilters, ...sourceInsightFilters];
}
function normalizeSourceFilterForDashboard(filter, sourceInsightMeasures) {
    if (!isMeasureValueFilter(filter)) {
        return [filter];
    }
    const measureRef = resolveSourceMeasureRef(filterMeasureRef(filter), sourceInsightMeasures);
    if (!measureRef) {
        return [];
    }
    return [
        {
            measureValueFilter: {
                ...filter.measureValueFilter,
                measure: measureRef,
            },
        },
    ];
}
function includedSourceFilters(sourceFilters, includedFilterObjRefs) {
    return sourceFilters.filter((sourceFilter) => {
        return includedFilterObjRefs.some((includedFilterObjRef) => isMatchingSourceInsightFilter(sourceFilter, includedFilterObjRef));
    });
}
