package dev.kaizen.app.db

import dev.kaizen.app.net.KaizenApi
import kotlinx.coroutines.flow.Flow

class MessageRepository(private val dao: MessageDao) {

    fun observeMessages(convId: String): Flow<List<MessageEntity>> =
        dao.observeByConversation(convId)

    suspend fun getCached(convId: String): List<MessageEntity> =
        dao.getByConversation(convId)

    suspend fun fetchAndCache(baseUrl: String, token: String, convId: String) {
        val stored = KaizenApi.fetchMessages(baseUrl, token, convId)
        val entities = stored.mapIndexed { i, m -> m.toEntity(convId, i) }
        dao.deleteByConversation(convId)
        dao.upsertAll(entities)
    }

    suspend fun cacheMessages(convId: String, messages: List<MessageEntity>) {
        dao.upsertAll(messages)
    }

    suspend fun prefetchMissing(baseUrl: String, token: String, conversationIds: List<String>) {
        val cached = dao.cachedConversationIds().toSet()
        for (id in conversationIds) {
            if (id in cached) continue
            try {
                fetchAndCache(baseUrl, token, id)
            } catch (_: Exception) { }
        }
    }
}
