import { getItem, searchItems } from "@esri/arcgis-rest-portal";
import { isGuid } from "../utils/is-guid";
import { getItemBySlug } from "../items/slugs";
import { getContentEnrichments } from "./_fetch";
import { fetchItemEnrichments } from "../items/_enrichments";
import { composeContent } from "./compose";
import { maybeConcat } from "../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
 */
export 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 (isGuid(identifier)) {
        // get item by id
        item = await getItem(identifier, options);
    }
    else {
        // if it is a slug, fetch item by typeKeyword slug, from portal
        item = await 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 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 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) || getContentEnrichments(item);
    const enrichments = await fetchItemEnrichments(item, enrichmentsToFetch, options);
    // compose into IHubContent
    const content = composeContent(item, Object.assign(Object.assign({ requestOptions: options }, enrichments), { layerId: (options && options.layerId) || null, 
        // merge error arrays
        errors: maybeConcat([enrichments.errors]), usePortalAPIOnly: true }));
    return content;
};
//# sourceMappingURL=fetchContentPortal.js.map