package wang.yaojia.webterm.hostregistry

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import java.util.UUID

/**
 * Instrumented (device) contract tests for [DataStoreLastSessionStore]. Mirrors the
 * JVM in-memory tests plus the iOS `garbageStoredValueReadsBackAsNil` defence: a
 * value that is not a UUID reads back as null (untrusted at rest). Runs on a device
 * (no emulator here → compiled, deferred to device QA, plan §7).
 */
@RunWith(AndroidJUnit4::class)
class DataStoreLastSessionStoreTest {

    private fun newStore(): DataStoreLastSessionStore {
        val ctx = ApplicationProvider.getApplicationContext<Context>()
        val dataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create(
            produceFile = { ctx.preferencesDataStoreFile("last-session-test-${UUID.randomUUID()}") },
        )
        return DataStoreLastSessionStore(dataStore)
    }

    private val validSession = UUID.randomUUID().toString()

    @Test
    fun set_then_get_returns_same_sessionId() = runBlocking {
        val store = newStore()
        store.setLastSessionId(validSession, hostId = "host-1")

        assertEquals(validSession, store.lastSessionId("host-1"))
    }

    @Test
    fun unset_host_returns_null() = runBlocking {
        assertNull(newStore().lastSessionId("host-1"))
    }

    @Test
    fun setting_null_clears() = runBlocking {
        val store = newStore()
        store.setLastSessionId(validSession, hostId = "host-1")

        store.setLastSessionId(null, hostId = "host-1")

        assertNull(store.lastSessionId("host-1"))
    }

    @Test
    fun distinct_hosts_are_isolated() = runBlocking {
        val store = newStore()
        val a = UUID.randomUUID().toString()
        val b = UUID.randomUUID().toString()

        store.setLastSessionId(a, hostId = "host-a")
        store.setLastSessionId(b, hostId = "host-b")

        assertEquals(a, store.lastSessionId("host-a"))
        assertEquals(b, store.lastSessionId("host-b"))
    }
}
