(ns auto-ap.graphql.ezcater
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.graphql.utils :refer [assert-admin cleanse-query]]
   [auto-ap.search :as search]
   [com.walmartlabs.lacinia.util :refer [attach-resolvers]]
   [datomic.client.api :as dc]
   [auto-ap.graphql.utils :refer [attach-tracing-resolvers]]))

(defn search [context args _]
  (assert-admin (:id context))
  (let [search-query (cleanse-query (:query args))]
    (for [[id name] (search/search {:q search-query}
                                   "ezcater-caterer")]
      {:name name
       :id   (Long/parseLong id)})))

(defn rebuild-search-index []
  (search/full-index-query  
    (for [result (map first (dc/qseq '[:find (pull ?a [:ezcater-caterer/search-terms :db/id :ezcater-caterer/name])
                                       :in $
                                       :where [?a :ezcater-caterer/search-terms ]]
                                     (dc/db conn)))]
      {:id            (:db/id result)
       :name (:ezcater-caterer/name result)
       :text  (:ezcater-caterer/search-terms result)})
    "ezcater-caterer"))

(def objects
  {:ezcater_caterer  {:fields {:name   {:type 'String}
                               :id  {:type :id}}}})

(def queries
  {:search_ezcater_caterer {:type    '(list :search_result)
                    :args    {:query     {:type 'String}}
                    :resolve :search-ezcater-caterer}})

(def enums
  {})

(def resolvers
  {:search-ezcater-caterer search})

(defn attach [schema]
  (->
   (merge-with merge schema
               {:objects       objects
                :queries       queries
                :enums         enums})
   (attach-tracing-resolvers resolvers)))
