package com.example.elva.data.local

import android.content.Context
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 by preferencesDataStore(name = "elva_prefs")

class SessionManager(private val context: Context) {

    private val tokenKey = stringPreferencesKey(KEY_TOKEN)

    val token: Flow<String?> = context.dataStore.data.map { it[tokenKey] }

    suspend fun saveToken(value: String) {
        context.dataStore.edit { prefs ->
            prefs[tokenKey] = value
        }
    }

    suspend fun clearToken() {
        context.dataStore.edit { prefs ->
            prefs.remove(tokenKey)
        }
    }

    companion object {
        private const val KEY_TOKEN = "auth_token"
    }
}

