(ns auto-ap.datomic.users
  (:require
   [auto-ap.datomic :refer [conn]]
   [datomic.api :as dc]
   [datomic.api :as d]))

(defn find-or-insert! [{:keys [:user/provider :user/provider-id ] :as new-user}]
  (let [is-first-user?  (not (seq (dc/q [:find '?e
                                         :in '$
                                         :where '[?e :user/provider]]
                                        (dc/db conn))))
        user-id (ffirst (dc/q '[:find ?e
                               :in $ ?provider ?provider-id
                               :where [?e :user/provider ?provider]
                               [?e :user/provider-id ?provider-id]]
                              (dc/db conn) provider provider-id))
        result @(dc/transact conn [[:upsert-entity (cond-> (assoc new-user :db/id (or user-id "user")
                                                                  :user/last-login (java.util.Date.))
                                                     (not user-id) (assoc :user/role :user-role/none)
                                                     is-first-user? (assoc :user/role :user-role/admin))]])
        user-id (or user-id (get-in result [:tempids "user"]))]
    (update (dc/pull (dc/db conn)
                     '[*
                       {:user/clients [*]}
                       {:user/role [:db/ident]}]
                     user-id)
            :user/role :db/ident)))

