(ns auto-ap.datomic.accounts
  (:require [datomic.api :as d]
            [auto-ap.graphql.utils :refer [->graphql]]
            [auto-ap.datomic :refer [uri merge-query]]))
(defn <-datomic [a]
  (update a :account/applicability :db/ident))

(defn get-accounts
  ([]
   (get-accounts {}))
  ([args]
   (let [query (cond-> {:query {:find ['(pull ?e [* {:account/type [:db/ident :db/id]
                                                     :account/applicability [:db/ident :db/id]
                                                     :account/client-overrides [:db/id
                                                                                :account-client-override/name
                                                                                {:account-client-override/client [:db/id :client/name]}]}])]
                                :in ['$]
                                :where [['?e :account/name]]}
                        :args [(d/db (d/connect uri))]}
                 (:account-set args) (merge-query {:query {:in ['?account-set]
                                                           :where [['?e :account/account-set '?account-set]]}
                                                   :args [(:account-set args)]}))]
     (->>
      (d/query query)
      (map first)
      (map <-datomic)))))

(defn get-by-id [id]
  (let [query {:query {:find ['(pull ?e [* {:account/type [:db/ident :db/id]
                                            :account/applicability [:db/ident :db/id]
                                            :account/client-overrides [:db/id
                                                                       :account-client-override/name
                                                                       {:account-client-override/client [:db/id :client/name]}]}])]
                       :in ['$ '?e]}
               :args [(d/db (d/connect uri) ) id]}]
    (->>
     (d/query query)
     (map first)
     (map <-datomic)
     first)))

(defn get-account-by-numeric-code-and-sets [numeric-code sets]
  (let [query (cond-> {:query {:find ['(pull ?e [* {:account/type [:db/ident :db/id]}])]
                               :in ['$ '?numeric-code]
                               :where ['[?e :account/numeric-code ?numeric-code]]}
                       :args [(d/db (d/connect uri)) numeric-code]})]
    (->>
     (d/query query)
     (map first)
     (map <-datomic)
     (first))))

#_(get-account-by-numeric-code-and-sets 5110 nil)
