/**
 Data Fetching for Sponsored Search.
 */
import { ads } from "../../api/typings/constants";
import { asString, isNullOrEmpty } from "../../foundation/json-parsing/server-data";
import { attributeAsDictionary } from "../../foundation/media/attributes";
import { dataCollectionFromDataContainer, } from "../../foundation/media/data-structure";
import { allProductVariantIdsForData, productVariantDataForData, productVariantIDForVariantData, } from "../product-page/product-page-variants";
import { adLogger } from "./search-ads";
import * as content from "../content/content";
// region exports
/**
 * Fetch the set of processed search ads with the raw adverts in the sequential response.
 * @param sponsoredSearchRequestData The request data to fetch processed ads for.
 * @param searchTerm The search term to fetch processed adverts for.
 * @param fetchResponse The promise that will resolve to the response.
 * @returns A promise that will provide `SponsoredSearchNativeAdvertData`. Note that even error conditions are represented in the result for instrumentation purposes.
 */
export async function fetchSponsoredSearchNativeAdvertData(objectGraph, sponsoredSearchRequestData, searchTerm, fetchResponse) {
    var _a;
    if (!sponsoredSearchRequestData.validAdRequest()) {
        adLogger(objectGraph, `ODML fetch skipped - Malformed request`);
        return {
            adverts: [],
            odmlSuccess: false,
        };
    }
    /**
     * This is a weird path where we:
     * 1. Fetch response from search
     * 2. Pass parts of the response back to native to be modified by SearchAds.
     */
    const response = await fetchResponse;
    const adverts = sponsoredSearchAdvertsFromResponse(objectGraph, response);
    const organics = sponsoredSearchOrganicsFromResponse(objectGraph, response, 1); // per POR, only 1 organic for now.
    try {
        if (!objectGraph.isAvailable(ads)) {
            adLogger(objectGraph, `ODML fetch skipped - Unsupported client`);
            return {
                adverts: adverts,
                odmlSuccess: false,
            };
        }
        else {
            const processedAdverts = await objectGraph.ads.processAdvertsForSponsoredSearch(adverts, organics, searchTerm, objectGraph.bag.sponsoredSearchODMLTimeout, objectGraph.client.isPhone || objectGraph.client.isPad);
            if (!processedAdverts.odmlSuccess) {
                adLogger(objectGraph, `ODML processing failed`);
            }
            else {
                adLogger(objectGraph, `ODML processing completed`);
            }
            return {
                adverts: (_a = processedAdverts.adverts) !== null && _a !== void 0 ? _a : adverts,
                odmlSuccess: processedAdverts.odmlSuccess,
                installedStates: processedAdverts.installedStates,
                appliedPolicy: processedAdverts.appliedPolicy,
                appStates: processedAdverts.appStates,
            };
        }
    }
    catch (e) {
        adLogger(objectGraph, `ODML fetch failed - ${e}`);
        return {
            adverts: adverts,
            odmlSuccess: false,
        };
    }
}
// endregion
// region internals
/**
 * Build the search advert models from the response.
 */
function sponsoredSearchAdvertsFromResponse(objectGraph, response) {
    const adverts = dataCollectionFromDataContainer(response.results["ads-result"]);
    const bridgedAdverts = [];
    for (const ad of adverts) {
        const id = asString(ad, "id");
        const adData = attributeAsDictionary(ad, "iads");
        if (isNullOrEmpty(id) || isNullOrEmpty(adData)) {
            continue;
        }
        let productVariantId = null;
        let allProductVariantIds = null;
        if (objectGraph.bag.enableCPPInSearchAds) {
            const productVariantData = productVariantDataForData(objectGraph, ad);
            productVariantId = productVariantIDForVariantData(productVariantData);
            allProductVariantIds = allProductVariantIdsForData(objectGraph, ad);
        }
        bridgedAdverts.push({
            instanceId: objectGraph.random.nextUUID(),
            adamId: id,
            assetInformation: {},
            adData: adData,
            cppIds: allProductVariantIds,
            serverCppId: productVariantId,
            selectedCppId: productVariantId,
            appBinaryTraits: content.appBinaryTraitsFromData(objectGraph, ad),
        });
    }
    return bridgedAdverts;
}
/**
 * Build the search organic models from the response, up to `limit`.
 */
function sponsoredSearchOrganicsFromResponse(objectGraph, response, limit) {
    const organics = dataCollectionFromDataContainer(response.results.search);
    const bridgedOrganics = [];
    for (const result of organics) {
        const id = asString(result, "id");
        if (isNullOrEmpty(id)) {
            continue;
        }
        bridgedOrganics.push({
            adamId: id,
            assetInformation: {},
        });
    }
    return bridgedOrganics;
}
// endregion
//# sourceMappingURL=sponsored-search-fetching.js.map