(ns auto-ap.db.companies
  (:require [auto-ap.db.utils :refer [clj->db db->clj get-conn query execute!]]
            [auto-ap.entities.companies :as entity]
            [clojure.edn :as edn]
            [clojure.java.jdbc :as j]
            [honeysql.core :as sql]
            [honeysql.helpers :as helpers]))
(def all-fields #{:name :email :data :id})

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

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

(defn fields->data [x]
  (-> x
      (assoc-in [:data :bank-accounts] (:bank-accounts x))
      (assoc-in [:data :address] (:address x))
      (dissoc :bank-accounts)
      (dissoc :address)))

(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 upsert [id data]
  (-> (sql/build
       :update :companies
       :set (clj->db (select-keys (fields->data data) all-fields))
       :where [:= :id (if (int? id)
                        id
                        (Integer/parseInt id))])
      execute!) 
  (get-by-id (if (int? id)
               id
               (Integer/parseInt id))))



