package de.tsschulz.tt_tagebuch.shared.state

import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class AndroidTokenStorage(
    context: Context,
) : TokenStorage {

    private val prefs = EncryptedSharedPreferences.create(
        context,
        PREFS_NAME,
        MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build(),
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
    )

    override suspend fun load(): AuthTokens? = withContext(Dispatchers.Default) {
        val token = prefs.getString(KEY_TOKEN, null)
        val username = prefs.getString(KEY_USERNAME, null)
        if (token.isNullOrBlank() || username.isNullOrBlank()) null else AuthTokens(token, username)
    }

    override suspend fun save(tokens: AuthTokens) = withContext(Dispatchers.Default) {
        prefs.edit()
            .putString(KEY_TOKEN, tokens.token)
            .putString(KEY_USERNAME, tokens.username)
            .apply()
    }

    override suspend fun clear() = withContext(Dispatchers.Default) {
        prefs.edit()
            .remove(KEY_TOKEN)
            .remove(KEY_USERNAME)
            .apply()
    }

    private companion object {
        private const val PREFS_NAME = "tttagebuch_auth"
        private const val KEY_TOKEN = "token"
        private const val KEY_USERNAME = "username"
    }
}

