package app.closer.crypto

import android.content.Context
import app.closer.data.local.SecurePreferencesFactory
import com.google.crypto.tink.KeysetHandle
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Persists one-time answer keys locally (EncryptedSharedPreferences / Keystore-backed)
 * from the moment the user submits a sealed answer until the reveal key is released.
 *
 * Keys are keyed by questionId. After release the key is removed to prevent stale keys
 * from accumulating. If the user loses the device before releasing their key, the answer
 * cannot be revealed from this device (by design — the crypto is only as strong as the
 * local key store).
 */
@Singleton
class PendingAnswerKeyStore @Inject constructor(
    @ApplicationContext context: Context,
    private val sealedAnswerEncryptor: SealedAnswerEncryptor
) {
    private val prefs = SecurePreferencesFactory.encryptedSharedPreferences(context, PREFS_NAME)

    fun store(questionId: String, keyHandle: KeysetHandle) {
        prefs.edit()
            .putString(prefKey(questionId), sealedAnswerEncryptor.serializeKey(keyHandle))
            .apply()
    }

    fun load(questionId: String): KeysetHandle? = runCatching {
        val json = prefs.getString(prefKey(questionId), null) ?: return null
        sealedAnswerEncryptor.deserializeKey(json)
    }.getOrNull()

    fun remove(questionId: String) {
        prefs.edit().remove(prefKey(questionId)).apply()
    }

    fun hasPendingKey(questionId: String): Boolean = prefs.contains(prefKey(questionId))

    private fun prefKey(questionId: String) = "pending_answer_key_$questionId"

    private companion object {
        const val PREFS_NAME = "pending_answer_keys_secure"
    }
}
