package com.syncflow.ui.conflict

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syncflow.data.db.SyncConflictDao
import com.syncflow.data.db.entities.SyncConflictEntity
import com.syncflow.domain.model.ConflictResolution
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ConflictViewModel @Inject constructor(
    private val conflictDao: SyncConflictDao,
    savedState: SavedStateHandle,
) : ViewModel() {

    private val pairId = savedState.get<Long>("pairId")!!

    val conflicts = conflictDao.observeUnresolved(pairId)
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    fun resolve(conflict: SyncConflictEntity, resolution: ConflictResolution) {
        viewModelScope.launch { conflictDao.resolve(conflict.id, resolution) }
    }

    fun resolveAll(resolution: ConflictResolution) {
        viewModelScope.launch {
            conflicts.value.forEach { conflictDao.resolve(it.id, resolution) }
        }
    }
}
