import Foundation

/// Message packet (0x06) — sending and receiving encrypted messages.
struct PacketMessage: Packet {
    static let packetId = 0x06

    var fromPublicKey: String = ""
    var toPublicKey: String = ""
    var content: String = ""           // XChaCha20-Poly1305 encrypted (hex)
    var chachaKey: String = ""         // ECDH-encrypted key+nonce
    var timestamp: Int64 = 0
    var privateKey: String = ""        // Hash for server auth
    var messageId: String = ""
    var attachments: [MessageAttachment] = []
    var aesChachaKey: String = ""      // ChaCha key+nonce encrypted by sender

    func write(to stream: Stream) {
        // Match Android field order exactly
        stream.writeString(fromPublicKey)
        stream.writeString(toPublicKey)
        stream.writeString(content)
        stream.writeString(chachaKey)
        stream.writeInt64(timestamp)
        stream.writeString(privateKey)
        stream.writeString(messageId)
        stream.writeInt8(attachments.count)

        for attachment in attachments {
            stream.writeString(attachment.id)
            stream.writeString(attachment.preview)
            stream.writeString(attachment.blob)
            stream.writeInt8(attachment.type.rawValue)
            stream.writeString(attachment.transportTag)
            stream.writeString(attachment.transportServer)
        }
        stream.writeString(aesChachaKey)
    }

    mutating func read(from stream: Stream) {
        fromPublicKey = stream.readString()
        toPublicKey = stream.readString()
        content = stream.readString()
        chachaKey = stream.readString()
        timestamp = stream.readInt64()
        privateKey = stream.readString()
        messageId = stream.readString()

        let attachmentCount = max(stream.readInt8(), 0)
        var list: [MessageAttachment] = []
        for _ in 0..<attachmentCount {
            let attId = stream.readString()
            let attPreview = stream.readString()
            let attBlob = stream.readString()
            let attType = AttachmentType(rawValue: stream.readInt8()) ?? .image
            let attTransportTag = stream.readString()
            let attTransportServer = stream.readString()
            list.append(MessageAttachment(
                id: attId,
                preview: attPreview,
                blob: attBlob,
                type: attType,
                transportTag: attTransportTag,
                transportServer: attTransportServer
            ))
        }
        attachments = list
        aesChachaKey = stream.readString()
    }
}
