(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))
      (assoc-in [:data :print-as] (:print-as x))
      (dissoc :address)
      (dissoc :print-as)))

(def all-fields [:name
                 :print-as
                 :code
                 :id
                 :invoice-reminder-schedule
                 :primary-contact
                 :primary-email
                 :primary-phone
                 :secondary-contact
                 :secondary-email
                 :secondary-phone
                 :default-expense-account
                 :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)))
