package com.rosetta.messenger.ui.chats.models

import androidx.compose.runtime.Stable
import com.rosetta.messenger.data.Message
import com.rosetta.messenger.network.DeliveryStatus
import com.rosetta.messenger.network.MessageAttachment
import com.rosetta.messenger.network.SearchUser
import java.util.*

/**
 * Models and data classes for Chat Detail Screen
 * Extracted from ChatDetailScreen.kt for better organization
 */

/** Stable wrapper for SearchUser to optimize recompositions */
@Stable 
class StableSearchUser(val user: SearchUser)

/** Reply/Forward data inside a message */
data class ReplyData(
    val messageId: String,
    val senderName: String,
    val text: String,
    val isFromMe: Boolean,
    val isForwarded: Boolean = false,
    val forwardedFromName: String = "",  // Имя оригинального отправителя для атрибуции
    val attachments: List<MessageAttachment> = emptyList(),  // 🖼️ Для превью фото в reply
    val senderPublicKey: String = "",  // Для расшифровки attachments в reply
    val recipientPrivateKey: String = "",  // Для расшифровки attachments в reply
    val chachaKey: String = "",  // Ключ оригинального сообщения для расшифровки attachments
    val chachaKeyPlainHex: String = ""  // Hex plainKeyAndNonce оригинального сообщения (для cross-platform forward)
)

/** Legacy message model (for compatibility) */
data class ChatMessage(
    val id: String,
    val text: String,
    val isOutgoing: Boolean,
    val timestamp: Date,
    val status: MessageStatus = MessageStatus.SENT,
    val showDateHeader: Boolean = false,
    val replyData: ReplyData? = null,
    val forwardedMessages: List<ReplyData> = emptyList(),  // Multiple forwarded messages (desktop parity)
    val attachments: List<MessageAttachment> = emptyList(),
    val chachaKey: String = "",  // Для расшифровки attachments
    val chachaKeyPlainHex: String = "",  // Hex plainKeyAndNonce для forward
    val senderPublicKey: String = "",
    val senderName: String = ""
)

/** Message delivery and read status */
enum class MessageStatus {
    SENDING,
    SENT,
    DELIVERED,
    READ,
    ERROR
}

/** Avatar colors for consistent user identification */
data class AvatarColors(
    val backgroundColor: androidx.compose.ui.graphics.Color,
    val textColor: androidx.compose.ui.graphics.Color
)

// Extension function to convert Message to ChatMessage
fun Message.toChatMessage() = ChatMessage(
    id = messageId,
    text = content,
    isOutgoing = isFromMe,
    timestamp = Date(timestamp),
    status = when (deliveryStatus) {
        DeliveryStatus.WAITING -> MessageStatus.SENDING
        DeliveryStatus.DELIVERED -> if (isRead) MessageStatus.READ else MessageStatus.DELIVERED
        DeliveryStatus.ERROR -> MessageStatus.ERROR
        DeliveryStatus.READ -> MessageStatus.READ
    }
)
