import * as serverData from "../../../foundation/json-parsing/server-data";
/**
 * This is a workaround for Search Focus Page based on existing metrics tech debt in Search Results Page.
 *
 * # Context
 * - In CrystalB, impressions for SFP now includes a recent searches shelf which needs to update dynamically as searches are performed.
 *
 * # 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 populates `parentId` as normal
 * 2. `event-linter` iterates through the impressions, finds the parent containers, and adds parent impression ids.
 * 3. Native generates `impressionParentId` as normal where possible.
 *
 * # 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.
 * 3. We need to dynamically update the recent searches shelf every time a search is performed.
 *
 * See `search-results-impressions` for more background.
 */
/**
 * Update the `impression` field, attributing impressionParentIds per workaround above.
 * @param eventFields Event fields to modify **in place**.
 */
export function decorateImpressionParentId(eventFields) {
    var _a;
    const impressions = serverData.asArrayOrEmpty(eventFields, "impressions");
    // Find result parent id.
    let recentsParentImpressionId;
    for (const impression of impressions) {
        const canonicalId = serverData.asString(impression, "canonicalId");
        if (canonicalId === "R8804") {
            recentsParentImpressionId = (_a = serverData.asString(impression, "impressionId")) !== null && _a !== void 0 ? _a : undefined; // *NOT* id.
            break;
        }
    }
    if (!recentsParentImpressionId) {
        return;
    }
    // Update impressions for search results
    eventFields["impressions"] = impressions.map((impression) => {
        const canonicalId = serverData.asString(impression, "canonicalId");
        const impressionType = serverData.asString(impression, "impressionType");
        if (serverData.isNullOrEmpty(canonicalId) &&
            impressionType === "link" &&
            impression != null &&
            serverData.asString(impression, "impressionParentId") == null) {
            impression["impressionParentId"] = recentsParentImpressionId;
        }
        return impression;
    });
}
//# sourceMappingURL=search-focus-impressions.js.map