package wang.yaojia.webterm.hostregistry

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

/**
 * In-memory [HostStore]. Lives in `main` (not `test`) on purpose — it doubles for
 * the DataStore store in this module's contract tests AND in the AW4 ViewModel
 * tests (mirrors the iOS `InMemoryHostStore` actor).
 *
 * A [Mutex] serializes the read-modify-write in [upsert]/[remove] so concurrent
 * callers can't interleave; the state is a value snapshot replaced wholesale on
 * every change (no in-place mutation of a shared reference).
 */
public class InMemoryHostStore(
    initial: List<Host> = emptyList(),
) : HostStore {
    private val mutex = Mutex()

    // Defensive copy so an external mutable list handed to the ctor can't alias
    // our state; replaced wholesale on every write.
    private var hosts: List<Host> = initial.toList()

    override suspend fun loadAll(): List<Host> = mutex.withLock { hosts }

    override suspend fun upsert(host: Host): List<Host> = mutex.withLock {
        val updated = hosts.upserting(host)
        hosts = updated
        updated
    }

    override suspend fun remove(id: String): List<Host> = mutex.withLock {
        val updated = hosts.removing(id)
        hosts = updated
        updated
    }
}
