package no.svorka.mcms.core

import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey

/**
 * Encrypted credential storage (Android Keystore-backed), the analogue of the
 * iOS Keychain wrapper. Never store secrets in plain SharedPreferences.
 */
class KeychainStore(context: Context) {
    private val prefs: SharedPreferences = run {
        val masterKey = MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build()
        EncryptedSharedPreferences.create(
            context,
            "mcms_credentials",
            masterKey,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
        )
    }

    fun get(key: String): String? = prefs.getString(key, null)
    fun set(key: String, value: String) { prefs.edit().putString(key, value).apply() }
    fun delete(key: String) { prefs.edit().remove(key).apply() }
}
