package com.rosetta.messenger.network

/**
 * Search packet (ID: 0x03)
 * Search for users by username or public key
 */
class PacketSearch : Packet() {
    var privateKey: String = ""
    var search: String = ""
    var users: List<SearchUser> = emptyList()

    override fun getPacketId(): Int = 0x03

    override fun receive(stream: Stream) {
        privateKey = stream.readString()
        search = stream.readString()
        val userCount = stream.readInt16() // Int16, not Int32!
        val usersList = mutableListOf<SearchUser>()
        for (i in 0 until userCount) {
            // Order: username, title, publicKey, verified, online (matching React Native)
            val user = SearchUser(
                username = stream.readString(),
                title = stream.readString(),
                publicKey = stream.readString(),
                verified = stream.readInt8(),
                online = stream.readInt8()
            )
            usersList.add(user)
        }
        users = usersList
    }

    override fun send(): Stream {
        val stream = Stream()
        stream.writeInt16(getPacketId())
        stream.writeString(privateKey)
        stream.writeString(search)
        // Desktop parity: packet always includes users count block.
        // For client requests this is 0, but field must be present for server parser.
        stream.writeInt16(users.size)
        users.forEach { user ->
            stream.writeString(user.username)
            stream.writeString(user.title)
            stream.writeString(user.publicKey)
            stream.writeInt8(user.verified)
            stream.writeInt8(user.online)
        }
        return stream
    }
}
