const fp = require('lodash/fp')

const elastic = require('./index')

const toBody = message =>
  fp.pick([
    'timestamp',
    'from',
    'to',
    'text',
  ], message)

const indexMessage = message => {
  return elastic.index({
    index: 'messages',
    type: 'message',
    id: message.id,
    body: toBody(message),
  })
}

const indexMessages = messages => {
  return elastic.bulk({
    body: fp.flatMap(message => [
      { index: { _index: 'messages', _type: 'message', _id: message.id }},
      toBody(message),
    ], messages),
  })
}

const searchMessages = async (channel, query, limit, afterTimestamp) => {
  let body = {
    size: limit,
    sort: [{ timestamp: { order: 'desc' }}],
    query: {
      bool: {
        filter: fp.concat(
          { term: { to: channel }},
          !query.nick ? [] : { term: { from: query.nick }}
        ),
        must: !query.text ? [] : [{
          match: {
            text: {
              query: query.text,
              operator: 'and',
              fuzziness: 'auto',
            }
          },
        }],
      },
    },
  }

  if (afterTimestamp) {
    body.search_after = [+afterTimestamp]
  }

  const { hits } = await elastic.search({
    index: 'messages',
    type: 'message',
    body,
  })

  return hits
}

module.exports = { indexMessage, indexMessages, searchMessages }

@@ -616,16 +616,245 @@
 p) =%3E %7B%0A
+  const %7B text, nick %7D = query%0A%0A  const isPhraseSearch = fp.some(delimeter =%3E (%0A    fp.startsWith(delimeter, text) && fp.endsWith(delimeter, text)%0A  ), %5B'%22', '%5C''%5D)%0A  const phraseText = isPhraseSearch ? text.slice(1, -1) : null%0A%0A
   let bo
@@ -1023,22 +1023,16 @@
        !
-query.
 nick ? %5B
@@ -1051,22 +1051,16 @@
 %7B from: 
-query.
 nick %7D%7D%0A
@@ -1085,22 +1085,16 @@
  must: !
-query.
 text ? %5B
@@ -1098,18 +1098,58 @@
 ? %5B%5D : %5B
-%7B
 %0A
+          isPhraseSearch%0A          ? %7B%0A  
         
@@ -1155,20 +1155,29 @@
    match
+_phrase
 : %7B%0A
+  
         
@@ -1190,43 +1190,135 @@
 xt: 
-%7B%0A              query:
+phraseText,%0A            %7D,%0A          %7D%0A          : %7B%0A            match: %7B%0A              text: %7B%0A               
  query
-.
+: 
 text,%0A
+  
     
@@ -1358,16 +1358,18 @@
         
+ 
+ 
 fuzzines
@@ -1383,33 +1383,51 @@
 o',%0A            
-%7D
+  %7D,%0A            %7D,
 %0A          %7D,%0A  
@@ -1432,17 +1432,16 @@
         
-%7D
 %5D,%0A     

Add phrase search for finding terms in same order