package com.inou.clawdnode.security

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

/**
 * Secure token storage using Android EncryptedSharedPreferences.
 * Hardware-backed encryption on supported devices.
 */
class TokenStore(context: Context) {
    
    private val masterKey = MasterKey.Builder(context)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()
    
    private val prefs = EncryptedSharedPreferences.create(
        context,
        "clawdnode_secure_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
    
    var gatewayUrl: String?
        get() = prefs.getString(KEY_GATEWAY_URL, null)
        set(value) = prefs.edit().putString(KEY_GATEWAY_URL, value).apply()
    
    var gatewayToken: String?
        get() = prefs.getString(KEY_GATEWAY_TOKEN, null)
        set(value) = prefs.edit().putString(KEY_GATEWAY_TOKEN, value).apply()
    
    var nodeId: String?
        get() = prefs.getString(KEY_NODE_ID, null)
        set(value) = prefs.edit().putString(KEY_NODE_ID, value).apply()
    
    val isConfigured: Boolean
        get() = !gatewayUrl.isNullOrEmpty() && !gatewayToken.isNullOrEmpty()
    
    fun clear() {
        prefs.edit()
            .remove(KEY_GATEWAY_URL)
            .remove(KEY_GATEWAY_TOKEN)
            .remove(KEY_NODE_ID)
            .apply()
    }
    
    companion object {
        private const val KEY_GATEWAY_URL = "gateway_url"
        private const val KEY_GATEWAY_TOKEN = "gateway_token"
        private const val KEY_NODE_ID = "node_id"
    }
}
