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 SavedSearchDto( val id: String = "ss-${UUID.randomUUID().toString().take(8)}", val ownerUserId: String, val name: String, val dealType: String = "", val segment: String = "", val marz: String = "", val priceMin: Long? = null, val priceMax: Long? = null, val rooms: Int? = null, val query: String = "", val seenSnapshot: Int = 0, val seenListingIds: List = emptyList(), val notifyEnabled: Boolean = true, val createdAtIso: String = java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(java.time.LocalDateTime.now()), ) internal class SavedSearchesStore( private val gson: Gson, private val file: Path, ) { private val lock = Any() fun listForUser(userId: String): List = synchronized(lock) { load().filter { it.ownerUserId == userId } } fun add(dto: SavedSearchDto): SavedSearchDto = synchronized(lock) { val list = load().toMutableList() list.add(0, dto) persist(list) dto } 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 } fun markSeen(id: String, userId: String, currentIds: List): SavedSearchDto? = 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(seenSnapshot = currentIds.size, seenListingIds = currentIds) list[idx] = updated persist(list) updated } 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 } }