(ns auto-ap.jobs.load-historical-sales
  (:require
   [auto-ap.datomic :refer [conn]]
   [auto-ap.jobs.core :refer [execute]]
   [auto-ap.square.core3 :as square3]
   [clj-time.coerce :as coerce]
   [clj-time.core :as time]
   [clj-time.periodic :as per]
   [auto-ap.logging :as alog]
   [config.core :refer [env]]
   [datomic.api :as dc]))


(defn historical-load-sales [client days]
  (alog/info ::new-sales-loading :client (:client/code client) :days days)
  (let [client (dc/pull (dc/db auto-ap.datomic/conn)
                       square3/square-read
                       client)
        days (cond-> days (string? days) ( #(Long/parseLong %)))]
    (doseq [square-location (:client/square-locations client)
            :when           (:square-location/client-location square-location)]
      
      (println "orders")
      (doseq [d (per/periodic-seq (time/plus (time/today) (time/days (- days)))
                                  (time/plus (time/today) (time/days 2))
                                  (time/days 1))]
        (println d)
        @(square3/upsert client square-location (coerce/to-date-time d) (coerce/to-date-time (time/plus d (time/days 1)))))

      (println "refunds")
     @(square3/upsert-refunds client square-location)
     @(square3/upsert-payouts  client square-location (time/plus (time/now) (time/days (- days))) (time/now)))))


(defn load-historical-sales [args]
  (let [{:keys [days client]} args
        client (cond-> client 
                 ( string? client) ( #( Long/parseLong %)))]
    (historical-load-sales client days)))

(defn -main [& _]
  (execute "load-historical-sales" #(load-historical-sales (:args env))))
