package app.closer.data.local

import android.content.Context
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class PendingInviteStore @Inject constructor(
    @ApplicationContext context: Context
) {
    private val prefs = SecurePreferencesFactory.encryptedSharedPreferences(context, PREFS_NAME)

    data class PendingInvite(val code: String, val recoveryPhrase: String)

    fun save(code: String, recoveryPhrase: String) {
        prefs.edit()
            .putString(KEY_CODE, code)
            .putString(KEY_PHRASE, recoveryPhrase)
            .putLong(KEY_CREATED_AT, System.currentTimeMillis())
            .apply()
    }

    fun load(): PendingInvite? {
        val code = prefs.getString(KEY_CODE, null) ?: return null
        val phrase = prefs.getString(KEY_PHRASE, null) ?: return null
        val age = System.currentTimeMillis() - prefs.getLong(KEY_CREATED_AT, 0L)
        if (age > TTL_MS) { clear(); return null }
        return PendingInvite(code, phrase)
    }

    fun clear() = prefs.edit().clear().apply()

    companion object {
        private const val PREFS_NAME = "closer_pending_invite"
        private const val KEY_CODE = "code"
        private const val KEY_PHRASE = "phrase"
        private const val KEY_CREATED_AT = "created_at"
        private const val TTL_MS = 24L * 60 * 60 * 1000
    }
}
