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

/**
 * Preferences-DataStore-backed [HostStore]. The whole host list is ONE JSON string
 * under [HOSTS_KEY], serialized by [HostCodec]. Reads decode + reconstruct (dropping
 * records whose baseUrl no longer validates); writes are an atomic read-modify-write
 * via [DataStore.edit], reusing the shared immutable list transforms.
 *
 * The [DataStore] is injected (constructed from a Context in :app DI) so this class
 * has no Android-framework surface of its own; its behaviour is verified instrumented
 * (androidTest) on a device.
 */
public class DataStoreHostStore(
    private val dataStore: DataStore<Preferences>,
) : HostStore {

    override suspend fun loadAll(): List<Host> =
        HostCodec.decode(dataStore.data.first()[HOSTS_KEY])

    override suspend fun upsert(host: Host): List<Host> =
        writeTransform { it.upserting(host) }

    override suspend fun remove(id: String): List<Host> =
        writeTransform { it.removing(id) }

    private suspend fun writeTransform(transform: (List<Host>) -> List<Host>): List<Host> {
        lateinit var updated: List<Host>
        dataStore.edit { prefs ->
            updated = transform(HostCodec.decode(prefs[HOSTS_KEY]))
            prefs[HOSTS_KEY] = HostCodec.encode(updated)
        }
        return updated
    }

    private companion object {
        val HOSTS_KEY = stringPreferencesKey("hosts")
    }
}
