package com.seven.ikar.kotlin.core.local

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query

@Dao
interface CachedChatMessageDao {
    @Query(
        """
        SELECT * FROM cached_chat_messages
        WHERE owner_user_id = :ownerUserId AND chat_id = :chatId
        ORDER BY sent_at DESC
        LIMIT :limit
        """
    )
    suspend fun loadLatestMessages(
        ownerUserId: String,
        chatId: String,
        limit: Int
    ): List<CachedChatMessageEntity>

    @Query(
        """
        SELECT * FROM cached_chat_messages
        WHERE owner_user_id = :ownerUserId AND chat_id = :chatId AND is_optimistic = 1
        ORDER BY sent_at ASC
        """
    )
    suspend fun loadOptimisticMessages(
        ownerUserId: String,
        chatId: String
    ): List<CachedChatMessageEntity>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(messages: List<CachedChatMessageEntity>)

    @Query(
        """
        DELETE FROM cached_chat_messages
        WHERE owner_user_id = :ownerUserId AND chat_id = :chatId AND message_id = :messageId
        """
    )
    suspend fun deleteMessage(
        ownerUserId: String,
        chatId: String,
        messageId: String
    )

    @Query(
        """
        DELETE FROM cached_chat_messages
        WHERE owner_user_id = :ownerUserId AND chat_id = :chatId
        """
    )
    suspend fun clearChat(ownerUserId: String, chatId: String)
}
