import { searchItems } from "@esri/arcgis-rest-portal";
import { TYPEKEYWORD_SLUG_PREFIX } from "../../items/_internal/slugs";
import { getItemTypeFromMatchableType } from "./getItemTypeFromMatchableType";
import { getWithDefault } from "../../objects/get-with-default";
export async function matchByKeywordSearch(type, identifier, context) {
    const result = {
        identifier,
        type,
        matcher: "keyword-search",
        num: 0,
        matches: [],
    };
    // Considered using hubSearch here, but this is much less code to execute
    // Construct typekeyword filter
    const keyword = identifier.startsWith(`${TYPEKEYWORD_SLUG_PREFIX}|`)
        ? identifier
        : [TYPEKEYWORD_SLUG_PREFIX, identifier].join("|");
    let filter = `typekeywords:"${keyword}"`;
    // if the type is specific enough, add it to the Filter, accounting for Enterprise
    const itemType = getItemTypeFromMatchableType(type, !!context.isPortal);
    if (itemType) {
        // add type to the filter
        filter = `${filter} AND type:"${itemType}"`;
    }
    const opts = {
        // This uses filter so it's an exact match
        filter,
    };
    // Add auth or portal to the search options
    if (context.requestOptions.authentication) {
        opts.authentication = context.requestOptions.authentication;
    }
    else {
        opts.portal = context.requestOptions.portal;
    }
    // execute the search against the portal api
    const response = await searchItems(opts);
    // Convert results to IMatch[]
    const matches = response.results.map((item) => ({
        id: item.id,
        type: item.type,
        name: item.title,
        identifier: getWithDefault(item, "properties.slug", item.id),
    }));
    result.num = matches.length;
    result.matches = matches;
    return result;
}
//# sourceMappingURL=matchByKeywordSearch.js.map