(ns auto-ap.entities.transaction-rule
  (:require [auto-ap.entities.transaction-rule-account :as transaction-rule-account]
            [clojure.spec.alpha :as s]
            [clojure.string :as str]))

(s/def ::client (s/nilable map?))
(s/def ::description (s/nilable (s/and string?
                                       #( #?@(:clj (try
                                                     (re-pattern %)
                                                     true
                                                     (catch Exception _
                                                       false))
                                              :cljs (try
                                                      (re-pattern %)
                                                      true
                                                      (catch js/Error _
                                                        false)))))))
(s/def ::amount-gte (s/or :double (s/nilable double?)
                          :string (s/nilable string?)))
(s/def ::amount-lte (s/or :double (s/nilable double?)
                          :string (s/nilable string?)))
(s/def ::dom-gte (s/nilable int?))
(s/def ::dom-lte (s/nilable int?))
(s/def ::note (s/nilable string?))
(s/def ::bank-account (s/nilable map?))
(s/def ::vendor (s/nilable map?))
(s/def ::yodlee-merchant (s/nilable map?))
(s/def ::accounts (s/coll-of ::transaction-rule-account/transaction-rule-account :min-count 1))

(s/def ::transaction-rule (s/and (s/keys :req-un [::client
                                                  ::description
                                                  ::amount-gte
                                                  ::amount-lte
                                                  ::dom-gte
                                                  ::dom-lte
                                                  ::note
                                                  ::bank-account
                                                  ::vendor
                                                  ::accounts]
                                         :opt-un [::yodlee-merchant])

                                 (s/or :description-required #(not (str/blank? (:description %)))
                                       :merchant-required #(not (nil? (:yodlee-merchant %))))))
