package wang.yaojia.webterm.di

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 dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import wang.yaojia.webterm.hostregistry.DataStoreHostStore
import wang.yaojia.webterm.hostregistry.DataStoreLastSessionStore
import wang.yaojia.webterm.hostregistry.HostStore
import wang.yaojia.webterm.hostregistry.LastSessionStore
import javax.inject.Singleton

/**
 * Persistence boundary (A15 → A12): the non-secret UI state stores over ONE Preferences DataStore.
 * The host list ([HostStore], key `"hosts"`) and per-host last-session id ([LastSessionStore], key
 * `"lastSessionId.<hostId>"`) use disjoint keys, so they safely share one DataStore file. Secret
 * material (the device cert) never lives here — that is the Tink store in [TlsModule].
 */
@Module
@InstallIn(SingletonComponent::class)
public object StorageModule {

    @Provides
    @Singleton
    public fun provideDataStore(
        @ApplicationContext context: Context,
    ): DataStore<Preferences> =
        PreferenceDataStoreFactory.create { context.preferencesDataStoreFile(DATASTORE_NAME) }

    @Provides
    @Singleton
    public fun provideHostStore(dataStore: DataStore<Preferences>): HostStore =
        DataStoreHostStore(dataStore)

    @Provides
    @Singleton
    public fun provideLastSessionStore(dataStore: DataStore<Preferences>): LastSessionStore =
        DataStoreLastSessionStore(dataStore)

    private const val DATASTORE_NAME: String = "webterm"
}
