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

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

(defn edit-user [context {:keys [edit_user] :as args} value]
  (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 %)) ))]
    
    
    (audit-transact (-> [{: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)))
                    (:id context))
    (->graphql
     (d-users/get-by-id (:id edit_user)))))

