package com.jishisongfu.duobibi.ui.records

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.db.Cluster
import com.jishisongfu.duobibi.data.repo.PriceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NewRecordViewModel @Inject constructor(
    private val repo: PriceRepository,
) : ViewModel() {

    val clusters: StateFlow<List<Cluster>> = repo.observeAllClusters()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun save(title: String, price: Double, sourceApp: String, clusterId: Long?, onDone: () -> Unit) {
        viewModelScope.launch {
            repo.insertManualRecord(title.trim(), price, sourceApp, clusterId)
            onDone()
        }
    }
}
