package com.estateunified.panel import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.UUID internal data class TaskDto( val id: String = "task-${UUID.randomUUID().toString().take(8)}", val ownerUserId: String, val title: String, val dueAtIso: String, val kind: String = "GENERIC", val dealId: String? = null, val listingId: String? = null, val leadId: String? = null, var status: String = "OPEN", val note: String = "", val createdAtIso: String = java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(java.time.LocalDateTime.now()), var updatedAtIso: String = java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(java.time.LocalDateTime.now()), ) internal class TasksStore( private val gson: Gson, private val file: Path, ) { private val lock = Any() fun listForUser(userId: String): List = synchronized(lock) { load().filter { it.ownerUserId == userId } .sortedWith(compareBy { it.status == "DONE" }.thenBy { it.dueAtIso }) } fun add(dto: TaskDto): TaskDto = synchronized(lock) { val list = load().toMutableList() list.add(0, dto) persist(list) dto } fun setStatus(id: String, userId: String, status: String): TaskDto? = synchronized(lock) { val list = load().toMutableList() val idx = list.indexOfFirst { it.id == id && it.ownerUserId == userId } if (idx < 0) return@synchronized null val updated = list[idx].copy( status = status, updatedAtIso = java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(java.time.LocalDateTime.now()), ) list[idx] = updated persist(list) updated } fun delete(id: String, userId: String): Boolean = synchronized(lock) { val list = load().toMutableList() val removed = list.removeIf { it.id == id && it.ownerUserId == userId } if (removed) persist(list) removed } private fun load(): MutableList { if (!Files.isRegularFile(file)) return mutableListOf() val text = Files.readString(file, StandardCharsets.UTF_8) if (text.isBlank()) return mutableListOf() return runCatching { gson.fromJson>(text, listType) ?: mutableListOf() }.getOrElse { mutableListOf() } } private fun persist(list: List) { Files.createDirectories(file.toAbsolutePath().parent) Files.writeString(file, gson.toJson(list), StandardCharsets.UTF_8) } companion object { private val listType = object : TypeToken>() {}.type } }