package com.example.todokmp.db

import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import com.example.todokmp.model.Priority
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow

class TodoRepository(driverFactory: DatabaseDriverFactory) {
    private val database = TodoDatabase(driverFactory.createDriver())
    private val queries = database.todoQueries

    fun getAllTodos(): Flow<List<TodoEntity>> {
        return queries.selectAll().asFlow().mapToList(Dispatchers.Default)
    }

    fun addTodo(title: String, category: String, priority: Priority) {
        queries.insert(
            title = title,
            completed = false,
            category = category,
            priority = priority.name.lowercase(),
            created_at = System.currentTimeMillis()
        )
    }

    fun toggleTodo(id: Long, completed: Boolean) {
        queries.toggleCompleted(completed = completed, id = id)
    }

    fun updateTodo(id: Long, title: String, category: String, priority: Priority) {
        queries.update(
            title = title,
            category = category,
            priority = priority.name.lowercase(),
            id = id
        )
    }

    fun deleteTodo(id: Long) {
        queries.delete(id = id)
    }
}
