package com.estateunified.panel import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonParser import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.util.UUID internal class UserListingsStore( private val gson: Gson, private val file: Path, ) { private val lock = Any() fun absolutePath(): String = file.toAbsolutePath().normalize().toString() fun readAll(): List = synchronized(lock) { if (!Files.isRegularFile(file)) return emptyList() val text = Files.readString(file, StandardCharsets.UTF_8) if (text.isBlank()) return emptyList() return try { val arr = JsonParser.parseString(text).asJsonArray arr.mapNotNull { if (it.isJsonObject) it.asJsonObject else null } } catch (_: Exception) { emptyList() } } fun add(payload: JsonObject): JsonObject { synchronized(lock) { val list = readAll().toMutableList() val id = payload.getAsJsonPrimitive("id")?.asString?.trim().takeUnless { it.isNullOrBlank() } ?: "owner-${UUID.randomUUID()}" payload.addProperty("id", id) list.removeAll { it.getAsJsonPrimitive("id").asString == id } list.add(0, payload) persist(list) return payload } } fun delete(id: String): Boolean { if (!id.startsWith("owner-")) return false synchronized(lock) { val list = readAll().toMutableList() val removed = list.removeIf { it.getAsJsonPrimitive("id")?.asString == id } if (removed) persist(list) return removed } } private fun persist(rows: List) { val parent = file.toAbsolutePath().parent Files.createDirectories(parent) val arr = JsonArray() rows.forEach { arr.add(it) } Files.writeString(file, gson.toJson(arr), StandardCharsets.UTF_8) } }