import { searchItems } from "@esri/arcgis-rest-portal";
import { getItemTypeFromMatchableType } from "./getItemTypeFromMatchableType";
import { getWithDefault } from "../../objects/get-with-default";
/**
 * Match by a title search
 * Handles searching by title: "%identifier.replace('-', ' ')%" and type: {type}
 * @param type
 * @param identifier
 * @param context
 * @returns
 */
export async function matchByTitleSearch(type, identifier, context) {
    const result = {
        identifier,
        type,
        matcher: "title-search",
        num: 0,
        matches: [],
    };
    let filter = `title:"%${identifier.replace(/-/g, " ")}%"`;
    // 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 q so it's a fuzzy match
        q: 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=matchByTitleSearch.js.map