package com.cottondb.android.platform import android.content.Context import android.content.SharedPreferences import com.cottondb.android.search.SEARCH_RECENTS_CAP import com.cottondb.android.search.SearchRecentsStore import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonPrimitive /** * Device-local search query history. The app manifest excludes its preferences from backup. * * Search queries are not vault values. This adapter never receives, reads, or saves a secret * payload, and it deliberately keeps no in-memory copy beyond SharedPreferences' own cache. */ class AndroidSearchRecentsStore private constructor( private val preferences: SharedPreferences, ) : SearchRecentsStore { constructor(context: Context, preferenceName: String = PREFERENCE_NAME) : this( context.applicationContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE), ) override fun load(): List { val stored = try { preferences.getString(RECENTS_KEY, null) } catch (failure: Throwable) { throw SearchRecentsStoreException(failure) } ?: return emptyList() return try { val array = Json.parseToJsonElement(stored) as? JsonArray ?: throw IllegalArgumentException() require(array.size <= SEARCH_RECENTS_CAP) array.map { entry -> (entry as? JsonPrimitive)?.takeIf(JsonPrimitive::isString)?.content ?: throw IllegalArgumentException() }.also { values -> require(values.all(String::isNotBlank)) require(values.map { it.lowercase(java.util.Locale.ROOT) }.toSet().size == values.size) } } catch (failure: Throwable) { throw SearchRecentsStoreException(failure) } } override fun save(recents: List) { require(recents.size <= SEARCH_RECENTS_CAP) { "Search recents exceed their maximum." } // apply() updates the process cache first and schedules disk work off the UI path. preferences.edit() .putString(RECENTS_KEY, JsonArray(recents.map(::JsonPrimitive)).toString()) .apply() } companion object { internal const val PREFERENCE_NAME = "search-recents-v1" internal const val RECENTS_KEY = "queries" } } /** Persisted content is deliberately not named: it can contain a person's search queries. */ class SearchRecentsStoreException(cause: Throwable? = null) : IllegalStateException( "Saved search recents are unavailable.", cause, )