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

import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Index
import androidx.room.Query
import androidx.room.Upsert

@Entity(
    tableName = "cached_chats",
    primaryKeys = ["owner_user_id", "chat_id"],
    indices = [
        Index(value = ["owner_user_id", "is_archived", "is_pinned"]),
        Index(value = ["owner_user_id", "last_activity_at"])
    ]
)
data class CachedChatEntity(
    @ColumnInfo(name = "owner_user_id")
    val ownerUserId: String,
    @ColumnInfo(name = "chat_id")
    val chatId: String,
    @ColumnInfo(name = "last_activity_at")
    val lastActivityAt: String?,
    @ColumnInfo(name = "is_pinned")
    val isPinned: Boolean,
    @ColumnInfo(name = "is_archived")
    val isArchived: Boolean,
    @ColumnInfo(name = "unread_count")
    val unreadCount: Int,
    @ColumnInfo(name = "payload_json")
    val payloadJson: String,
    @ColumnInfo(name = "updated_at_millis")
    val updatedAtMillis: Long
)

@Dao
interface CachedChatDao {
    @Query(
        """
        SELECT * FROM cached_chats
        WHERE owner_user_id = :ownerUserId
        ORDER BY is_pinned DESC, last_activity_at DESC
        """
    )
    suspend fun loadChats(ownerUserId: String): List<CachedChatEntity>

    @Upsert
    suspend fun upsert(chats: List<CachedChatEntity>)

    @Query("DELETE FROM cached_chats WHERE owner_user_id = :ownerUserId")
    suspend fun clear(ownerUserId: String)
}
