package com.syncflow.ui.log

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syncflow.data.db.SyncEventDao
import com.syncflow.data.db.SyncPairDao
import com.syncflow.data.db.entities.SyncEventEntity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

data class LogEntry(val event: SyncEventEntity, val pairName: String)

@HiltViewModel
class LogViewModel @Inject constructor(
    syncEventDao: SyncEventDao,
    syncPairDao: SyncPairDao,
) : ViewModel() {

    val entries = combine(
        syncEventDao.observeAll(500),
        syncPairDao.observeAll(),
    ) { events, pairs ->
        val pairNames = pairs.associateBy({ it.id }, { it.name })
        events.map { LogEntry(it, pairNames[it.syncPairId] ?: "Unknown") }
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
}
