package wang.yaojia.webterm.hostregistry

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.flow.first
import wang.yaojia.webterm.wire.Validation

/**
 * Preferences-DataStore-backed [LastSessionStore]. Each host's last sessionId is
 * ONE string entry under `"lastSessionId.<hostId>"` (mirrors the iOS UserDefaults
 * key prefix), so distinct hosts never collide.
 *
 * The stored value crosses a storage boundary → validated on read with the frozen
 * v4-specific [Validation.isValidSessionId] (the SAME guard the wire codec applies
 * to server-issued ids), so a non-v4/garbage value reads back as null rather than
 * being handed to the attach path (untrusted at rest). The [DataStore] is injected;
 * behaviour is verified instrumented (androidTest) on a device.
 */
public class DataStoreLastSessionStore(
    private val dataStore: DataStore<Preferences>,
) : LastSessionStore {

    override suspend fun lastSessionId(hostId: String): String? {
        val raw = dataStore.data.first()[keyFor(hostId)]
        return raw?.takeIf(Validation::isValidSessionId)
    }

    override suspend fun setLastSessionId(sessionId: String?, hostId: String) {
        val key = keyFor(hostId)
        dataStore.edit { prefs ->
            if (sessionId == null) prefs.remove(key) else prefs[key] = sessionId
        }
    }

    private fun keyFor(hostId: String) = stringPreferencesKey(KEY_PREFIX + hostId)

    private companion object {
        const val KEY_PREFIX = "lastSessionId."
    }
}
