package com.rugvedsarika.privatelog.utils

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

class PreferenceHelper(context: Context) {

    private val sharedPreferences = try {
        val masterKey = MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build()

        EncryptedSharedPreferences.create(
            context,
            PREFS_NAME,
            masterKey,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )
    } catch (e: Exception) {
        // Fallback or handle error (e.g. key store issues)
        // For strict security, we might crash or clear data, but for now just propagate or basic fallback logic could be added
        // Assuming success on standard devices
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) 
    }

    companion object {
        private const val PREFS_NAME = "secure_prefs"
        private const val KEY_PIN = "user_pin"
    }

    fun savePin(pin: String) {
        sharedPreferences.edit().putString(KEY_PIN, pin).apply()
    }

    fun getPin(): String? {
        return sharedPreferences.getString(KEY_PIN, null)
    }

    fun isPinSet(): Boolean {
        return !sharedPreferences.getString(KEY_PIN, null).isNullOrEmpty()
    }

    fun clear() {
        sharedPreferences.edit().clear().apply()
    }

    fun getOrGenerateDatabaseKey(): ByteArray {
        val keyStr = sharedPreferences.getString("db_key", null)
        if (keyStr == null) {
            val key = ByteArray(32)
            java.security.SecureRandom().nextBytes(key)
            val newKeyStr = android.util.Base64.encodeToString(key, android.util.Base64.DEFAULT)
            sharedPreferences.edit().putString("db_key", newKeyStr).apply()
            return key
        }
        return android.util.Base64.decode(keyStr, android.util.Base64.DEFAULT)
    }
}
