"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchContentPortal = void 0;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const is_guid_1 = require("../utils/is-guid");
const slugs_1 = require("../items/slugs");
const _fetch_1 = require("./_fetch");
const _enrichments_1 = require("../items/_enrichments");
const compose_1 = require("./compose");
const _array_1 = require("../utils/_array");
/**
 * Fetch Content from ArcGIS Portal by id or slug
 * Temporary function to support migration from Hub Index to portal
 * Once released, this will be renamed fetchContent and the existing fetchContent facade
 * function will be removed.
 * @param identifier
 * @param options
 * @returns
 */
const fetchContentPortal = async (identifier, options) => {
    // Resolve content using the same logic as any other entity
    let item;
    // if id is a guid, fetch item by id from portal
    if ((0, is_guid_1.isGuid)(identifier)) {
        // get item by id
        item = await (0, arcgis_rest_portal_1.getItem)(identifier, options);
    }
    else {
        // if it is a slug, fetch item by typeKeyword slug, from portal
        item = await (0, slugs_1.getItemBySlug)(identifier, options);
        if (!item) {
            // try searching for an item by title using the slugs as a fallback
            const titleFromSlug = identifier.replace(/-/g, " ");
            const q = `title:"${titleFromSlug}"`;
            const searchResult = await (0, arcgis_rest_portal_1.searchItems)({
                q,
                authentication: options === null || options === void 0 ? void 0 : options.authentication,
                num: 1,
            });
            if (searchResult.results.length > 0) {
                const id = searchResult.results[0].id;
                item = await (0, arcgis_rest_portal_1.getItem)(id, options);
            }
            else {
                // attempted both slug options and got nothing back
                throw new Error(`Item not found for identifier: ${identifier}`);
            }
        }
    }
    // Now fetch the item enrichments and compose the content
    const enrichmentsToFetch = (options === null || options === void 0 ? void 0 : options.enrichments) || (0, _fetch_1.getContentEnrichments)(item);
    const enrichments = await (0, _enrichments_1.fetchItemEnrichments)(item, enrichmentsToFetch, options);
    // compose into IHubContent
    const content = (0, compose_1.composeContent)(item, Object.assign(Object.assign({ requestOptions: options }, enrichments), { layerId: (options && options.layerId) || null, 
        // merge error arrays
        errors: (0, _array_1.maybeConcat)([enrichments.errors]), usePortalAPIOnly: true }));
    return content;
};
exports.fetchContentPortal = fetchContentPortal;
//# sourceMappingURL=fetchContentPortal.js.map