package de.krisenvorrat.app.data.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Upsert
import de.krisenvorrat.app.data.db.entity.MessageEntity
import kotlinx.coroutines.flow.Flow

@Dao
internal interface MessageDao {

    @Upsert
    suspend fun upsert(message: MessageEntity)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertIfNotExists(message: MessageEntity)

    @Query("""
        SELECT * FROM messages 
        WHERE (sender_id = :myId AND receiver_id = :otherId) 
           OR (sender_id = :otherId AND receiver_id = :myId) 
        ORDER BY sent_at ASC
    """)
    fun getConversation(myId: String, otherId: String): Flow<List<MessageEntity>>

    @Query("SELECT * FROM messages WHERE is_pending = 1 ORDER BY sent_at ASC")
    suspend fun getPendingMessages(): List<MessageEntity>

    @Query("UPDATE messages SET is_pending = 0 WHERE id = :id")
    suspend fun markDelivered(id: String)
}
