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

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

(def all-fields [:name
                 :code
                 :id
                 :invoice-reminder-schedule
                 :primary-contact
                 :primary-email
                 :primary-phone
                 :secondary-contact
                 :secondary-email
                 :secondary-phone
                 :data])

(defn unparse [x]
  (-> (fields->data x)
      (select-keys all-fields)
      (clj->db)))

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

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

(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 :vendors
       :set (unparse data)
       :where [:= :id (if (int? id)
                        id
                        (Integer/parseInt id))])
      execute!) 
  (get-by-id (if (int? id)
               id
               (Integer/parseInt id))))

(defn insert [data]
  (let [[id] (-> (sql/build :insert-into :vendors
                            :values [(unparse data)])
                 execute!)]
    (println "inserted vendor: " data ", id " id)
    (get-by-id id)))

(defn find-with-reminders []
  (query (-> base-query
             (helpers/merge-where [:= :invoice-reminder-schedule "Weekly"]))))
