package pl.firmatpp.kierowca.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

private val Context.driverDataStore by preferencesDataStore(name = "driver_session")

class TokenStore(private val context: Context) {
    private val tokenKey = stringPreferencesKey("access_token")

    suspend fun save(token: String) {
        context.driverDataStore.edit { preferences ->
            preferences[tokenKey] = token
        }
    }

    suspend fun read(): String? = context.driverDataStore.data
        .map { it[tokenKey] }
        .first()

    suspend fun clear() {
        context.driverDataStore.edit { it.remove(tokenKey) }
    }
}
