(ns todo.fx
  (:require [re-frame.core :as rf]
            [todo.sqlite :as sqlite]))

(defonce db-instance (atom nil))

(rf/reg-fx
  :sqlite/init
  (fn [_]
    (-> (sqlite/open-db)
        (.then (fn [db]
                 (reset! db-instance db)
                 (-> (sqlite/init-db db)
                     (.then (fn [_]
                              (-> (sqlite/get-all-todos db)
                                  (.then (fn [rows]
                                           (rf/dispatch [:todos-loaded (js->clj rows :keywordize-keys true)])))))))))
        (.catch (fn [err] (js/console.error "SQLite init error:" err))))))

(rf/reg-fx
  :sqlite/insert
  (fn [{:keys [title category priority on-success]}]
    (when-let [db @db-instance]
      (-> (sqlite/insert-todo db title category priority)
          (.then (fn [result]
                   (when on-success
                     (rf/dispatch (conj on-success (.-lastInsertRowId ^js result))))))
          (.catch (fn [err] (js/console.error "Insert error:" err)))))))

(rf/reg-fx
  :sqlite/update
  (fn [{:keys [id title category priority]}]
    (when-let [db @db-instance]
      (-> (sqlite/update-todo-title db id title category priority)
          (.catch (fn [err] (js/console.error "Update error:" err)))))))

(rf/reg-fx
  :sqlite/toggle
  (fn [{:keys [id completed]}]
    (when-let [db @db-instance]
      (-> (sqlite/toggle-todo db id completed)
          (.catch (fn [err] (js/console.error "Toggle error:" err)))))))

(rf/reg-fx
  :sqlite/delete
  (fn [{:keys [id]}]
    (when-let [db @db-instance]
      (-> (sqlite/delete-todo db id)
          (.catch (fn [err] (js/console.error "Delete error:" err)))))))
