package wang.yaojia.webterm.hostregistry

import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import wang.yaojia.webterm.wire.HostEndpoint

/**
 * Contract tests for the in-Sources [InMemoryHostStore] double (which the AW4 VM
 * tests reuse). Same behaviour the DataStore store must exhibit; verified here at
 * JVM speed under virtual time.
 */
class InMemoryHostStoreTest {

    private fun host(id: String, name: String = "host-$id"): Host =
        Host(id = id, name = name, endpoint = requireNotNull(HostEndpoint.fromBaseUrl("http://10.0.0.1:3000")))

    @Test
    fun `loadAll returns the seeded hosts`() = runTest {
        val a = host("1")
        val store = InMemoryHostStore(listOf(a))

        assertEquals(listOf(a), store.loadAll())
    }

    @Test
    fun `upsert inserts then replaces same-id, and loadAll reflects it`() = runTest {
        val store = InMemoryHostStore()
        val a = host("1")

        assertEquals(listOf(a), store.upsert(a))
        // replace with same id
        val renamed = host("1", name = "renamed")
        assertEquals(listOf(renamed), store.upsert(renamed))
        assertEquals(listOf(renamed), store.loadAll())
    }

    @Test
    fun `remove drops the host, unknown id is a no-op`() = runTest {
        val a = host("1")
        val b = host("2")
        val store = InMemoryHostStore(listOf(a, b))

        assertEquals(listOf(a, b), store.remove("nope"))
        assertEquals(listOf(a), store.remove("2"))
        assertEquals(listOf(a), store.loadAll())
    }

    @Test
    fun `a list passed to the ctor is defensively copied`() = runTest {
        val seed = mutableListOf(host("1"))
        val store = InMemoryHostStore(seed)

        // Mutating the caller's list must not leak into the store.
        seed.add(host("2"))

        assertEquals(1, store.loadAll().size)
    }
}
