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

import com.seven.ikar.kotlin.core.model.ChatSummaryDto
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

class ChatListCache(
    private val dao: CachedChatDao,
    private val json: Json
) {
    suspend fun loadChats(ownerUserId: String): List<ChatSummaryDto> =
        dao.loadChats(ownerUserId)
            .mapNotNull { entity -> runCatching { json.decodeFromString<ChatSummaryDto>(entity.payloadJson) }.getOrNull() }

    suspend fun replaceChats(ownerUserId: String, chats: List<ChatSummaryDto>) {
        val now = System.currentTimeMillis()
        dao.clear(ownerUserId)
        if (chats.isEmpty()) {
            return
        }

        dao.upsert(
            chats.map { chat ->
                CachedChatEntity(
                    ownerUserId = ownerUserId,
                    chatId = chat.id,
                    lastActivityAt = chat.lastActivityAt,
                    isPinned = chat.isPinned,
                    isArchived = chat.isArchived,
                    unreadCount = chat.unreadCount,
                    payloadJson = json.encodeToString(chat),
                    updatedAtMillis = now
                )
            }
        )
    }
}
