package dev.kaizen.app.db

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

@Dao
interface ConversationDao {
    @Query("SELECT * FROM conversations ORDER BY pinned DESC, updatedAt DESC")
    fun observeAll(): Flow<List<ConversationEntity>>

    @Upsert
    suspend fun upsertAll(conversations: List<ConversationEntity>)

    @Upsert
    suspend fun upsert(conversation: ConversationEntity)

    @Query("DELETE FROM conversations")
    suspend fun deleteAll()

    @Query("DELETE FROM conversations WHERE id NOT IN (:keepIds)")
    suspend fun deleteExcept(keepIds: List<String>)

    @Query("UPDATE conversations SET title = :title WHERE id = :id")
    suspend fun updateTitle(id: String, title: String)

    @Transaction
    suspend fun replaceAll(conversations: List<ConversationEntity>) {
        if (conversations.isEmpty()) {
            deleteAll()
        } else {
            upsertAll(conversations)
            deleteExcept(conversations.map { it.id })
        }
    }

    @Query("SELECT cachedAt FROM conversations LIMIT 1")
    suspend fun lastCachedAt(): Long?

    @Query("SELECT id FROM conversations WHERE locked = 0")
    suspend fun allUnlockedIds(): List<String>
}
