package com.syncflow.data.security

import android.content.Context
import android.content.SharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class CredentialStore @Inject constructor(@ApplicationContext private val context: Context) {

    private val prefs: SharedPreferences by lazy {
        @Suppress("DEPRECATION")
        val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
        EncryptedSharedPreferences.create(
            "syncflow_credentials",
            masterKeyAlias,
            context,
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
        )
    }

    // ── Account credentials ───────────────────────────────────────────────────

    fun save(accountId: Long, credJson: String) {
        prefs.edit().putString(credKey(accountId), credJson).apply()
    }

    /** Returns null if no credential has been stored for this account yet. */
    fun getCredJson(accountId: Long): String? = prefs.getString(credKey(accountId), null)

    fun remove(accountId: Long) {
        prefs.edit().remove(credKey(accountId)).apply()
    }

    // ── PKCE verifiers and OAuth state (OAuth flow) ───────────────────────────

    fun savePkceVerifier(provider: String, verifier: String) {
        prefs.edit().putString(pkceKey(provider), verifier).apply()
    }

    fun getPkceVerifier(provider: String): String? = prefs.getString(pkceKey(provider), null)

    fun removePkceVerifier(provider: String) {
        prefs.edit().remove(pkceKey(provider)).apply()
    }

    // ── SFTP host key fingerprints (TOFU) ─────────────────────────────────────

    fun saveHostKey(host: String, port: Int, fingerprint: String) {
        prefs.edit().putString(hostKey(host, port), fingerprint).apply()
    }

    fun getHostFingerprint(host: String, port: Int): String? =
        prefs.getString(hostKey(host, port), null)

    // ── Key helpers ───────────────────────────────────────────────────────────

    private fun credKey(accountId: Long) = "cred_$accountId"
    private fun pkceKey(provider: String) = "pkce_$provider"
    private fun hostKey(host: String, port: Int) = "sshhost_${host}_$port"
}
