package com.jiooption.trading.security

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

/**
 * Encrypted SharedPreferences for secure token/credential storage
 */
class SecureStorage(context: Context) {

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

    private val prefs: SharedPreferences = EncryptedSharedPreferences.create(
        context,
        "binarypro_secure_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )

    fun putString(key: String, value: String) {
        prefs.edit().putString(key, value).apply()
    }

    fun getString(key: String, default: String = ""): String {
        return prefs.getString(key, default) ?: default
    }

    fun putBoolean(key: String, value: Boolean) {
        prefs.edit().putBoolean(key, value).apply()
    }

    fun getBoolean(key: String, default: Boolean = false): Boolean {
        return prefs.getBoolean(key, default)
    }

    fun putInt(key: String, value: Int) {
        prefs.edit().putInt(key, value).apply()
    }

    fun getInt(key: String, default: Int = 0): Int {
        return prefs.getInt(key, default)
    }

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

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

    // Convenience methods for auth
    fun saveSessionCookie(cookie: String) {
        putString("session_cookie", cookie)
    }

    fun getSessionCookie(): String = getString("session_cookie")

    fun saveUserCredentials(userId: String, name: String, email: String) {
        prefs.edit()
            .putString("user_id", userId)
            .putString("user_name", name)
            .putString("user_email", email)
            .putBoolean("is_logged_in", true)
            .apply()
    }

    fun isLoggedIn(): Boolean = getBoolean("is_logged_in")

    fun getUserId(): String = getString("user_id")
    fun getUserName(): String = getString("user_name")
    fun getUserEmail(): String = getString("user_email")

    fun clearAuth() {
        prefs.edit()
            .remove("session_cookie")
            .remove("user_id")
            .remove("user_name")
            .remove("user_email")
            .putBoolean("is_logged_in", false)
            .apply()
    }
}
