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

(defn add-bank-account-codes-schema [conn]
  [[{:db/ident :bank-account/code
     :db/valueType :db.type/string
     :db/unique :db.unique/identity
     :db/cardinality :db.cardinality/one
     :db/doc "A bank account's computer-friendly name"}]])


(defn add-bank-account-codes [conn]
  (let [db (d/db conn)
        all-bank-accounts (d/query {:query {:find ['?b '?original-id '?client-code]
                                            :in ['$]
                                            :where ['[?c :client/code ?client-code]
                                                    '[?c :client/bank-accounts ?b]
                                                    '[?b :bank-account/original-id ?original-id]]}
                                    :args [db]})]
    [(mapv (fn [[bank-account-id bank-account-code client-code ]]
             (let [[_ bank-account-code] (str/split bank-account-code #"-" )]
               {:db/id bank-account-id
                :bank-account/code (str client-code "-" bank-account-code)}))
           all-bank-accounts)]))

#_(add-bank-account-codes (d/connect uri))
