(ns todo.sqlite
  (:require ["expo-sqlite" :as SQLite]))

(defn open-db []
  (SQLite/openDatabaseAsync "todos.db"))

(defn init-db [^js db]
  (.execAsync db
    "CREATE TABLE IF NOT EXISTS todos (
       id INTEGER PRIMARY KEY AUTOINCREMENT,
       title TEXT NOT NULL,
       completed INTEGER DEFAULT 0,
       category TEXT DEFAULT 'Personal',
       priority TEXT DEFAULT 'medium',
       created_at INTEGER DEFAULT (strftime('%s','now'))
     );"))

(defn get-all-todos [^js db]
  (.getAllAsync db "SELECT * FROM todos ORDER BY created_at DESC"))

(defn insert-todo [^js db title category priority]
  (.runAsync db
    "INSERT INTO todos (title, category, priority) VALUES (?, ?, ?)"
    #js [title category priority]))

(defn update-todo-title [^js db id title category priority]
  (.runAsync db
    "UPDATE todos SET title = ?, category = ?, priority = ? WHERE id = ?"
    #js [title category priority id]))

(defn toggle-todo [^js db id completed]
  (.runAsync db
    "UPDATE todos SET completed = ? WHERE id = ?"
    #js [(if completed 1 0) id]))

(defn delete-todo [^js db id]
  (.runAsync db
    "DELETE FROM todos WHERE id = ?"
    #js [id]))
