(ns auto-ap.db.checks
  (:require [auto-ap.db.utils :refer [clj->db db->clj get-conn execute!] :as u]
            [auto-ap.entities.companies :as entity]
            [clojure.edn :as edn]
            [clojure.java.jdbc :as j]
            [honeysql.core :as sql]
            [honeysql.helpers :as helpers]))

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

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

(defn query [q]
  (map data->fields (u/query q)))

(defn get-all []
  (query base-query))

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

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

(defn insert! [row]
  (-> (j/insert! (get-conn)
                 :checks
                 (-> row
                     fields->data
                     clj->db))
      first
      db->clj
      data->fields))

(defn insert-multi! [rows]
  (->> (j/insert-multi! (get-conn)
                        :checks
                        (->> rows
                             (map fields->data)
                             (map clj->db)))
       (map db->clj)
       (map data->fields)))
