import { isSome } from "@jet/environment/types/optional";
import * as serverData from "../../../foundation/json-parsing/server-data";
/**
 * This is a workaround for existing metrics tech debt in Search Results Page.
 *
 * # Context
 * - In AzulC, impressions for SRP now includes 'containers' for search results and guided search tokens.
 * - The containers were added so tokens don't affect impression index, which search uses as a signal for ranking.
 *
 * # What is the Workaround?
 * The JetEngine Metrics API is designed to work s.t.:
 * 1. JS populates `parentId`, which JetEngine Metric APIs uses **internally** to refer to between `ImpressionMetrics`.
 * 2. Native generates `impressionParentId`, which is refers `impressionId` of parent assigned during serialization -
 *
 * Here, we instead:
 * 1. JS *doesn't* populate `parentId`
 * 2. `event-linter` iterates through the impressions, finds the parent containers, and adds parent impression ids.
 *
 * # Why Workaround?
 * 1. There are existing hacks for impression parents, e.g. fake `ad_container` and native child trackers w/ parent ID attribution.
 * 2. AppStore is stuck between old ASK metrics and new JE metrics APIs. Our JS builders and existing native metrics are intertwined in a way that makes using JS defined `parentId` attribution nontrivial.
 *
 * Note that we **don't** use this for attributing parent id workaround for `search-revisions`, i.e. guided search tokens.
 * This is because that codepath began from a clean slate, and uses JE metrics as-designed
 */
/**
 * Update the `impression` field, attributing impressionParentIds per workaround above.
 * @param eventFields Event fields to modify **in place**.
 */
export function decorateImpressionParentId(eventFields) {
    const impressions = serverData.asArrayOrEmpty(eventFields, "impressions");
    // Find result parent id.
    let resultsParentImpressionId;
    for (const impression of impressions) {
        const impressionType = serverData.asString(impression, "impressionType");
        if (isSome(impression) && impressionType === "SearchResults") {
            resultsParentImpressionId = impression["impressionId"]; // *NOT* id.
            break;
        }
    }
    if (!resultsParentImpressionId) {
        return;
    }
    // Update impressions for search results
    eventFields["impressions"] = impressions.map((impression) => {
        const impressionType = serverData.asString(impression, "impressionType");
        const isCardResult = impressionType === "card";
        const isEventModuleResult = impressionType === "eventModule";
        const isSearchResult = isCardResult || isEventModuleResult; // search results are cards and app events.
        if (isSome(impression) && isSearchResult) {
            impression["impressionParentId"] = resultsParentImpressionId;
        }
        return impression;
    });
}
//# sourceMappingURL=search-result-impressions.js.map