(ns auto-ap.graphql.users
  (:require [auto-ap.datomic.users :as d-users]
            [datomic.api :as d]
            [auto-ap.datomic :refer [uri]]
            [auto-ap.graphql.utils :refer [->graphql assert-admin]])) 

(def role->datomic-role {":none" :user-role/none
                         ":admin" :user-role/admin
                         ":user" :user-role/user})

(defn edit-user [context {:keys [edit_user] :as args} value]
  (println args edit_user)
  (assert-admin (:id context))
  (let [user (d-users/get-by-id (:id edit_user))
        new-clients (set (map #(Long/parseLong %) (:clients edit_user)))
        clients-to-remove (->> (:user/clients user)
                              (map :db/id)
                              (filter #(not (new-clients %)) ))]
    
    
    @(d/transact (d/connect uri)
                 
                 (doto (-> [{:db/id (:db/id user)
                             :user/role (role->datomic-role (:role edit_user))  
                             :user/clients new-clients}]
                           (into (map (fn [c] [:db/retract (:db/id user) :user/clients c]) clients-to-remove)))
                   clojure.pprint/pprint))
    (->graphql
     (d-users/get-by-id (:id edit_user)))))

