package wang.yaojia.webterm.hostregistry

import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/**
 * In-memory [LastSessionStore] double (in `main` so the AW4 ViewModel/cold-start
 * tests can inject it). A [Mutex] serializes writes; the per-host map is an
 * immutable snapshot replaced wholesale on every change (never mutated in place).
 */
public class InMemoryLastSessionStore : LastSessionStore {
    private val mutex = Mutex()
    private var byHost: Map<String, String> = emptyMap()

    override suspend fun lastSessionId(hostId: String): String? =
        mutex.withLock { byHost[hostId] }

    override suspend fun setLastSessionId(sessionId: String?, hostId: String) {
        mutex.withLock {
            byHost = if (sessionId == null) byHost - hostId else byHost + (hostId to sessionId)
        }
    }
}
