(ns auto-ap.datomic.migrate.rename-codes
  (:require [datomic.api :as d]
            [auto-ap.datomic :refer [uri]]
            [clojure.string :as str]))

(defn rename [old-code new-code conn ]
  (let [results (->> (d/query {:query {:find ['?e '?b '?bc]
                                 :in ['$ '?old-code]
                                   :where ['[?e :client/code ?old-code]
                                           '[?e :client/bank-accounts ?b]
                                           '[?b :bank-account/code ?bc]]}
                               :args [(d/db conn) old-code]})
                     (group-by first))
        
        #_#_[[id]] results]
    (for [[id change] results
          [_ ba-id ba-code] change]
      [{:db/id id
        :client/code new-code}
       {:db/id ba-id
        :bank-account/code (str/replace ba-code #"^.*-" (str new-code "-"))}])
    
    #_[{:db/id id
      :client/code new-code
      #_#_:client/bank-accounts (map)}]
    )
  )

(defn rename-codes-1 [conn]
  (let [result (apply concat [(rename  "WE" "WME" (d/connect uri))
                              (rename  "HM" "HIM" (d/connect uri))
                              (rename  "BES" "SBE" (d/connect uri))
                              (rename  "BES" "SBE" (d/connect uri))
                              (rename  "ORA" "OMG" (d/connect uri))
                              (rename  "INT" "IGC" (d/connect uri))
                              (rename  "MV" "MVSC" (d/connect uri))])]
    (if (seq (seq result))
      result
      [[]]))
  )

