import { b as KlevuEvents, c as KlevuTypeOfRequest, f as KlevuTypeOfRecord } from './klevuFetch.js';
import './KlevuDomEvents.js';
import './KlevuApiRawResponse.js';
import './KlevuSearchSorting.js';

/**
 * cleans query term to improve search results
 *
 * @param term search term to be cleaned
 */
function cleanSearchQuery(term) {
    return (term
        // whitespace
        .replace(/\s{2,}/g, " ")
        // extra spaces
        .replace(/\s\s+/g, " ")
        // white space in end
        .trim()
        // to lowercase
        .toLocaleLowerCase());
}

/**
 * This modifier should be used in the case when user hits enter (or presses button) to see
 * all results from search.
 *
 * @category Modifier
 * @returns
 */
function sendSearchEvent(override) {
    return {
        klevuModifierId: "sendSearchEvent",
        onResult: (res, f) => {
            var _a;
            if (!f.params) {
                return res;
            }
            const { id, term } = f.params;
            if (!id || !term) {
                return res;
            }
            const meta = (_a = res.queriesById(id)) === null || _a === void 0 ? void 0 : _a.meta;
            if (!meta) {
                return res;
            }
            KlevuEvents.search({
                term,
                totalResults: meta.totalResultsFound,
                typeOfSearch: meta.typeOfSearch,
                override,
            });
            if (!f.params) {
                f.params = {};
            }
            f.params.searchSendEventSent = true;
            return res;
        },
    };
}

const defaults = {
    id: "search",
    limit: 5,
    typeOfRecords: [KlevuTypeOfRecord.Product],
};
/**
 * Create a basic search to Klevu backend. Default ID for this query is `search`
 *
 *
 * @category Query
 * @param term Search term from input
 * @param options {@link KlevuSearchOptions}
 * @returns
 */
function search(term, options, ...modifiers) {
    const params = Object.assign(Object.assign({}, defaults), options);
    const cleanedTerm = cleanSearchQuery(term);
    const query = {
        id: params.id,
        typeOfRequest: KlevuTypeOfRequest.Search,
        settings: Object.assign({ query: {
                term: cleanedTerm,
            } }, params),
    };
    return {
        klevuFunctionId: "search",
        params: Object.assign(Object.assign({}, params), { term }),
        queries: [query],
        modifiers,
    };
}

export { sendSearchEvent as a, cleanSearchQuery as c, search as s };

//# sourceMappingURL=search.js.map