'use strict';

const _ = require('lodash');

/**
 * @summary Retrieve the maximum number of records that must be inspected during
 *          a Lexicon search to find matching entries for the input search text.
 * @param  {String}   text  Text string intended as the input for a Lexicon search
 * @param  {Function} callback Function called on process completion, with standard (err, result) signature.
 * @return {Number}   The maximum number of records that must be inspected during
 *                    a Lexicon search to find matching entries for the input search text.
 *
 * @memberof LexiconService
 * @instance
 */
function lookupTermFrequency(text, cb) {
    if (_.isEmpty(text)) {
        return cb(this.error('INVALID_SEARCH_TERM', text));
    }

    const tokens = text
        .trim()
        .toUpperCase()
        .split(' ');

    const findObject = {
        query: { word: { $in: _.castArray(tokens) } },
        options: { sort: { count: 1 } },
    };

    this.find('ExpressionTerms', findObject, (err, res) => {
        if (err) {
            return cb(err);
        }

        const firstTerm = _.first(res);
        const result = _.get(firstTerm, 'count', 0);

        cb(null, result);
    });
}

module.exports = {
    lookupTermFrequency,
};
