"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.matchByKeywordSearch = matchByKeywordSearch;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const slugs_1 = require("../../items/_internal/slugs");
const getItemTypeFromMatchableType_1 = require("./getItemTypeFromMatchableType");
const get_with_default_1 = require("../../objects/get-with-default");
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(`${slugs_1.TYPEKEYWORD_SLUG_PREFIX}|`)
        ? identifier
        : [slugs_1.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 = (0, getItemTypeFromMatchableType_1.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 (0, arcgis_rest_portal_1.searchItems)(opts);
    // Convert results to IMatch[]
    const matches = response.results.map((item) => ({
        id: item.id,
        type: item.type,
        name: item.title,
        identifier: (0, get_with_default_1.getWithDefault)(item, "properties.slug", item.id),
    }));
    result.num = matches.length;
    result.matches = matches;
    return result;
}
//# sourceMappingURL=matchByKeywordSearch.js.map