package de.oaa.xxx.app.data.local

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

private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "xxx_session")

class TokenStore(private val context: Context) {

    companion object {
        private val JWT_KEY = stringPreferencesKey("jwt_token")
        private val USER_ID_KEY = stringPreferencesKey("user_id")
        private val USER_NAME_KEY = stringPreferencesKey("user_name")
    }

    val jwtToken: Flow<String?> = context.dataStore.data.map { it[JWT_KEY] }
    val userId: Flow<String?> = context.dataStore.data.map { it[USER_ID_KEY] }
    val userName: Flow<String?> = context.dataStore.data.map { it[USER_NAME_KEY] }

    suspend fun saveToken(token: String) {
        context.dataStore.edit { it[JWT_KEY] = token }
    }

    suspend fun saveUser(userId: String, name: String) {
        context.dataStore.edit {
            it[USER_ID_KEY] = userId
            it[USER_NAME_KEY] = name
        }
    }

    suspend fun clear() {
        context.dataStore.edit { it.clear() }
    }
}
