package dev.kaizen.app.db

import dev.kaizen.app.net.ConversationSummary
import dev.kaizen.app.net.FetchResult
import dev.kaizen.app.net.KaizenApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class ConversationRepository(private val dao: ConversationDao) {

    fun observeAll(): Flow<List<ConversationSummary>> =
        dao.observeAll().map { list -> list.map { it.toSummary() } }

    suspend fun refresh(baseUrl: String, token: String) {
        when (val r = KaizenApi.fetchConversations(baseUrl, token)) {
            is FetchResult.Ok -> {
                val entities = r.data.map { it.toEntity() }
                dao.replaceAll(entities)
            }
            is FetchResult.Fail -> { /* cache stays, no crash */ }
        }
    }

    suspend fun insertOptimistic(id: String, title: String) {
        dao.upsert(ConversationEntity(
            id = id,
            title = title,
            locked = false,
            pinned = false,
            updatedAt = java.time.Instant.now().toString(),
            cachedAt = System.currentTimeMillis(),
        ))
    }

    suspend fun updateTitle(id: String, title: String) {
        dao.updateTitle(id, title)
    }

    suspend fun lastCachedAt(): Long? = dao.lastCachedAt()

    suspend fun allUnlockedIds(): List<String> = dao.allUnlockedIds()
}
