package com.bytelyst.platform

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

/**
 * EncryptedSharedPreferences-backed secure storage.
 *
 * Replaces Keychain on iOS. Uses Android Keystore for key material.
 * Each app gets its own namespace via [applicationId].
 */
class BLSecureStore(
    context: Context,
    applicationId: String,
) {
    private val prefs: SharedPreferences = try {
        val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
        EncryptedSharedPreferences.create(
            "${applicationId}_secure_store",
            masterKeyAlias,
            context,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
        )
    } catch (_: Exception) {
        // Fallback to plain SharedPreferences if encryption fails (e.g., test environment)
        context.getSharedPreferences("${applicationId}_secure_store_fallback", Context.MODE_PRIVATE)
    }

    fun save(key: String, value: String): Boolean {
        return prefs.edit().putString(key, value).commit()
    }

    fun read(key: String): String? {
        return prefs.getString(key, null)
    }

    fun delete(key: String): Boolean {
        return prefs.edit().remove(key).commit()
    }

    fun clear(): Boolean {
        return prefs.edit().clear().commit()
    }

    fun contains(key: String): Boolean {
        return prefs.contains(key)
    }
}
