package com.rosetta.messenger.network.connection

import com.rosetta.messenger.data.AccountManager

class AuthRestoreService(
    private val getAccountManager: () -> AccountManager?,
    private val addLog: (String) -> Unit,
    private val shortKeyForLog: (String) -> String,
    private val authenticate: (publicKey: String, privateHash: String) -> Unit
) {
    fun restoreAuthFromStoredCredentials(
        preferredPublicKey: String? = null,
        reason: String = "background_restore"
    ): Boolean {
        val accountManager = getAccountManager()
        if (accountManager == null) {
            addLog("⚠️ restoreAuthFromStoredCredentials skipped: AccountManager is not bound")
            return false
        }
        val publicKey =
            preferredPublicKey?.trim().orEmpty().ifBlank {
                accountManager.getLastLoggedPublicKey().orEmpty()
            }
        val privateHash = accountManager.getLastLoggedPrivateKeyHash().orEmpty()
        if (publicKey.isBlank() || privateHash.isBlank()) {
            addLog(
                "⚠️ restoreAuthFromStoredCredentials skipped (pk=${publicKey.isNotBlank()} hash=${privateHash.isNotBlank()} reason=$reason)"
            )
            return false
        }
        addLog("🔐 Restoring auth from cache reason=$reason pk=${shortKeyForLog(publicKey)}")
        authenticate(publicKey, privateHash)
        return true
    }
}
