(ns auto-ap.graphql.ezcater
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.graphql.utils :refer [assert-admin attach-tracing-resolvers]]
   [clojure.string :as str]
   [datomic.api :as dc]))

(defn search [context args _]
  (assert-admin (:id context))
  (for [[id name] (dc/q '[:find ?i ?n
                          :in $ ?s
                          :where [?i :ezcater-caterer/name ?n]
                          [(clojure.string/upper-case ?n) ?n2]
                          [(clojure.string/includes? ?n2 ?s)]]
                        (dc/db conn)
                        (str/upper-case (:query args)))]
    {:name name
     :id   id}))


(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)))
