package com.syncflow.data.providers.sftp

import com.syncflow.data.security.CredentialStore
import net.schmizz.sshj.transport.verification.HostKeyVerifier
import java.security.MessageDigest
import java.security.PublicKey

/**
 * Trust-On-First-Use SSH host key verifier.
 *
 * First connection to a host: fingerprint is stored in EncryptedSharedPreferences and accepted.
 * Subsequent connections: stored fingerprint must match — mismatch aborts (possible MITM).
 */
class TofuHostKeyVerifier(private val credentialStore: CredentialStore) : HostKeyVerifier {

    override fun verify(hostname: String, port: Int, key: PublicKey): Boolean {
        val fingerprint = sha256Fingerprint(key)
        val stored = credentialStore.getHostFingerprint(hostname, port)
        return if (stored == null) {
            credentialStore.saveHostKey(hostname, port, fingerprint)
            true
        } else {
            stored == fingerprint
        }
    }

    // Return empty list so sshj uses server preference order for key exchange.
    // Our verify() will accept or reject whatever algorithm is negotiated.
    override fun findExistingAlgorithms(hostname: String, port: Int): List<String> = emptyList()

    private fun sha256Fingerprint(key: PublicKey): String {
        val digest = MessageDigest.getInstance("SHA-256").digest(key.encoded)
        return digest.joinToString(":") { "%02x".format(it) }
    }
}
