"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.explainQueryResult = explainQueryResult;
const util_1 = require("../util");
const explainFilter_1 = require("./_internal/explainFilter");
const utils_1 = require("./utils");
/**
 * Explain why a specific result was included in a Query.
 *
 * NOTE: This only works for entityType: "item" queries and does not
 * cover all possible permutations.
 * @param queryResult
 * @param query
 * @param requestOptions
 * @returns
 */
async function explainQueryResult(queryResult, query, requestOptions) {
    // Throw if the query is not for items
    if (query.targetEntity !== "item") {
        throw new Error(`explainQueryResult: Only queries with targetEntity: "item" are supported`);
    }
    // Expand the query so we have a standardized structure to work with
    const expandedQuery = (0, utils_1.expandPortalQuery)(query);
    // iterate the filters on the query and get explanations for each
    const filterExplanations = [];
    for (const filter of expandedQuery.filters) {
        const fe = await (0, explainFilter_1.explainFilter)(filter, queryResult, requestOptions);
        filterExplanations.push(fe);
    }
    // Collect up the reasons
    const included = filterExplanations.reduce((acc, explanation) => {
        if (!explanation.matched) {
            acc = false;
        }
        return acc;
    }, true);
    // Collect up all the reasons into a single array
    const summary = [];
    filterExplanations.forEach((fe) => {
        fe.reasons.forEach((predicateExplanation) => {
            predicateExplanation.reasons.forEach((reason) => {
                summary.push(reason);
            });
        });
    });
    // construct the result
    const result = {
        result: (0, util_1.cloneObject)(queryResult),
        query: (0, util_1.cloneObject)(query),
        matched: included,
        reasons: filterExplanations,
        summary,
    };
    return result;
}
//# sourceMappingURL=explainQueryResult.js.map