(ns auto-ap.graphql.utils
  (:require [clojure.string :as str]
            [buddy.auth :refer [throw-unauthorized]]
            [clojure.walk :as walk]))


(defn snake->kebab [s]
  (str/replace s #"_" "-"))

(defn kebab [x]
  (if (qualified-keyword? x)
    (keyword (snake->kebab (namespace x)) (snake->kebab (name x)) )
    (keyword (snake->kebab (name x)))))

(defn kebab->snake [s]
  (str/replace s #"-" "_"))

(defn snake [x]
  (keyword (kebab->snake (name x))))

(defn ->graphql [m]
  (walk/postwalk
    (fn [node]
      (cond

        (keyword? node)
        (snake node)

        :else
        node))
    m))

(defn <-graphql [m]
  (walk/postwalk
    (fn [node]
      (cond

        (keyword? node)
        (kebab node)

        :else
        node))
    m))


(defn assert-admin [id]
  (when-not (= "admin" (:user/role id))
    (throw-unauthorized)))

(defn can-see-client? [identity client]
  (when (not client)
    (println "WARNING - permission checking for null client"))
  (or (= "admin" (:user/role identity))
      ((set (map :db/id (:user/clients identity))) (:db/id client))
      ((set (map :db/id (:user/clients identity))) client)))

(defn assert-can-see-client [identity client]
  (when-not (can-see-client? identity client)
    (println "IDENTITY " identity " can not see company " client)
    (throw-unauthorized)))

(defn limited-clients [id]
  (cond
    (or 
    (= (:user/role id) "none"))
    []

    (= (:user/role id) "admin")
    nil

    (= (:user/role id) "user")
    (:user/clients id [])))
