package com.rosetta.messenger.data

private const val PLACEHOLDER_ACCOUNT_NAME = "Account"

fun resolveAccountDisplayName(publicKey: String, name: String?, username: String?): String {
    val normalizedName = name?.trim().orEmpty()
    if (
        normalizedName.isNotEmpty() &&
            !normalizedName.equals(PLACEHOLDER_ACCOUNT_NAME, ignoreCase = true) &&
            !looksLikePublicKeyAlias(normalizedName, publicKey)
    ) {
        return normalizedName
    }

    val normalizedUsername = username?.trim().orEmpty()
    if (normalizedUsername.isNotEmpty()) {
        return normalizedUsername
    }

    if (publicKey.isBlank()) {
        return PLACEHOLDER_ACCOUNT_NAME
    }

    return if (publicKey.length > 12) {
        "${publicKey.take(6)}...${publicKey.takeLast(4)}"
    } else {
        publicKey
    }
}

private fun looksLikePublicKeyAlias(name: String, publicKey: String): Boolean {
    if (publicKey.isBlank()) return false
    if (name.equals(publicKey, ignoreCase = true)) return true

    val compactKeyAlias =
        if (publicKey.length > 12) "${publicKey.take(6)}...${publicKey.takeLast(4)}" else publicKey
    if (name.equals(compactKeyAlias, ignoreCase = true)) return true

    val normalized = name.lowercase()
    val prefix = publicKey.take(6).lowercase()
    val suffix = publicKey.takeLast(4).lowercase()
    return normalized.startsWith(prefix) && normalized.endsWith(suffix) && normalized.contains("...")
}

fun isPlaceholderAccountName(name: String?): Boolean =
    name?.trim().orEmpty().equals(PLACEHOLDER_ACCOUNT_NAME, ignoreCase = true)
