import serialize from './serialize';

/**
 * Takes an array of options and a query string and returns matches.
 *
 * @typedef {Object} Searchable
 * @property {string} type
 * @property {Object} data
 *
 * @typedef {Object} Query
 * @property {string} query - the original query string
 * @property {string[]} tokens - tokenized query string
 *
 * @typedef {Object} SearchResult
 * @property {Query} query
 * @property {Searchable[]} results
 *
 * @param {Object} opts
 * @param {string} opts.query
 *        The query string that you want to search for
 * @param {Searchable[]} opts.options
 *        An array of searchable options
 * @returns {SearchResult}
 */
const search = function search({
  query,
  options,
  searchKey
}) {
  const optionsToCheck = options || [];
  const serializedQuery = serialize(query);
  const matches = optionsToCheck.map(data => {
    if (!data[searchKey]) {
      return null;
    }
    if (serializedQuery.every(q => data[searchKey].toLowerCase().includes(q))) {
      return {
        ...data
      };
    }
    return null;
  });
  return {
    query: {
      string: query,
      tokens: serializedQuery
    },
    results: matches.filter(Boolean)
  };
};
export default search;