package dev.kaizen.app.db

import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import kotlinx.coroutines.flow.Flow

@Dao
interface MessageDao {
    @Query("SELECT * FROM messages WHERE conversationId = :convId ORDER BY sortOrder")
    fun observeByConversation(convId: String): Flow<List<MessageEntity>>

    @Query("SELECT * FROM messages WHERE conversationId = :convId ORDER BY sortOrder")
    suspend fun getByConversation(convId: String): List<MessageEntity>

    @Upsert
    suspend fun upsertAll(messages: List<MessageEntity>)

    @Query("DELETE FROM messages WHERE conversationId = :convId")
    suspend fun deleteByConversation(convId: String)

    @Query("SELECT DISTINCT conversationId FROM messages")
    suspend fun cachedConversationIds(): List<String>

    @Query("UPDATE messages SET ttsUrl = :url, ttsVoice = :voice WHERE id = :messageId")
    suspend fun updateTts(messageId: String, url: String, voice: String)

    @Query("SELECT ttsUrl FROM messages WHERE id = :messageId AND ttsVoice = :voice")
    suspend fun getTtsUrl(messageId: String, voice: String): String?
}
