package pt.whatsms.gateway.data.entities

import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Relation

data class MessageWithRecipients(
    @Embedded val message: Message,
    @Relation(
        parentColumn = "id",
        entityColumn = "messageId",
    )
    val recipients: List<MessageRecipient>,
    @Relation(
        parentColumn = "id",
        entityColumn = "messageId",
    )
    val states: List<MessageState> = emptyList(),
    @ColumnInfo(name = "rowid")
    val rowId: Long = 0,
) {
    val state: pt.whatsms.gateway.domain.ProcessingState
        get() = when {
            recipients.any { it.state == pt.whatsms.gateway.domain.ProcessingState.Pending } -> pt.whatsms.gateway.domain.ProcessingState.Pending
            recipients.any { it.state == pt.whatsms.gateway.domain.ProcessingState.Processed } -> pt.whatsms.gateway.domain.ProcessingState.Processed

            recipients.all { it.state == pt.whatsms.gateway.domain.ProcessingState.Failed } -> pt.whatsms.gateway.domain.ProcessingState.Failed
            recipients.all { it.state == pt.whatsms.gateway.domain.ProcessingState.Delivered } -> pt.whatsms.gateway.domain.ProcessingState.Delivered
            else -> pt.whatsms.gateway.domain.ProcessingState.Sent
        }
}
