(ns auto-ap.db.users
  (:require [auto-ap.db.utils :refer [get-conn query db->clj clj->db]]
            [clojure.edn :as edn]
            [clojure.java.jdbc :as j]
            [honeysql.core :as sql]
            [honeysql.helpers :as helpers]))

(defn data->fields [x]
  (-> x
      (merge (:data x))
      (dissoc :data)))

(defn fields->data [x]
  (-> x
      (assoc-in [:data :role] (:role x))
      (assoc-in [:data :name] (:name x))
      (assoc-in [:data :companies] (:companies x))
      (dissoc :role)
      (dissoc :name)
      (dissoc :companies)))

(def base-query (sql/build :select :*
                           :from :users))

(defn get-all []
  (map data->fields (query base-query)))

(defn get-by-id [id]
  (first (map data->fields (query (-> base-query
                                      (helpers/merge-where [:= :id id]))))))

(defn find-or-insert! [row]
  (let [user (-> base-query
                 (helpers/merge-where [:and [:= :provider-id (:provider-id row)]
                                       [:= :provider (:provider row)]])
                 query
                 first
                 data->fields)]
    (if user
      user
      (-> (j/insert! (get-conn)
                     :users
                     (-> row
                         fields->data
                         clj->db))
          first
          db->clj
          data->fields))))


(defn update! [row]
  (j/update! (get-conn)
             :users
             (-> row (fields->data) (clj->db))
             ["id = ?" (:id row)]))
