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

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

(defn query [q]
  (u/query q))

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

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

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


(defn get-sum-by-invoice [id]
  (:sum (first (query (-> (helpers/select :%sum.amount)
                          (helpers/from :invoices-checks)
                          (helpers/merge-where [:= :invoice-id id])
                          )))))

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

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

(defn delete! [id]
  (j/delete! (get-conn) :invoices_checks ["id = ?" id]))

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