(ns auto-ap.graphql.plaid
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.graphql.utils
    :refer [assert-admin assert-present attach-tracing-resolvers cleanse-query]]
   [auto-ap.solr :as solr]
   [datomic.api :as dc]))

(defn delete-plaid-item [context args _]
  (assert-admin (:id context))
  (assert-present args :id)
  @(dc/transact conn [[:db/retractEntity (:id args)]])
  {:message "Item deleted."})

(defn search-merchants [context args _]
  (if-let [query (not-empty (cleanse-query (:query args)))]
    (let [search-query (str "name:(" query ")")]
      (for [{:keys [id name]} (solr/query solr/impl "plaid_merchants" {"query"  search-query
                                                                       "fields" "id, name"})]
        {:id   (Long/parseLong id)
         :name (first name)}))
    []))



(defn attach [schema]
  (-> 
   (merge-with merge schema
               {:objects {:plaid_link_result
                          {:fields {:token {:type 'String}} }

                          :plaid_item
                          {:fields {:external_id {:type 'String}
                                    :id {:type :id}
                                    :client {:type :client}
                                    :status {:type 'String}
                                    :last_updated {:type :iso_date}
                                    :accounts {:type '(list :plaid_account)}}}

                          :plaid_item_page {:fields {:plaid_items {:type '(list :plaid_item)}
                                                     :count {:type 'Int}
                                                     :total {:type 'Int}
                                                     :start {:type 'Int}
                                                     :end {:type 'Int}}}

                          :plaid_account
                          {:fields {:external_id {:type 'String}
                                    :id {:type :id}
                                    :balance {:type :money}
                                    :name {:type 'String}
                                    :number {:type 'String}}}}
                :queries {:search_plaid_merchants {:type '(list :plaid_merchant)
                                                  :args {:query {:type 'String}}
                                                  :resolve :search-plaid-merchants}}})
   (attach-tracing-resolvers {:search-plaid-merchants     search-merchants})))

