package com.jishisongfu.duobibi.ui.alert

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.db.AlertMode
import com.jishisongfu.duobibi.data.db.AlertStatus
import com.jishisongfu.duobibi.data.db.PriceAlert
import com.jishisongfu.duobibi.data.repo.PriceRepository
import com.jishisongfu.duobibi.util.AlertNotifier
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * 降价雷达 ViewModel —— 想买的(WANT)/ 已买的(BOUGHT)两段共用。
 * 列表为 reactive Flow;写操作 fire-and-forget;"立即查价"复用 batchCheckAlerts + 通知。
 */
@HiltViewModel
class AlertViewModel @Inject constructor(
    app: Application,
    private val repo: PriceRepository,
) : AndroidViewModel(app) {

    val wants: StateFlow<List<PriceAlert>> =
        repo.observeAlertsByMode(AlertMode.WANT)
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val boughts: StateFlow<List<PriceAlert>> =
        repo.observeAlertsByMode(AlertMode.BOUGHT)
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val readyCount: StateFlow<Int> =
        repo.observeReadyAlertCount()
            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)

    private val _refreshing = MutableStateFlow(false)
    val refreshing: StateFlow<Boolean> = _refreshing.asStateFlow()

    fun addWant(title: String, platform: String?, targetPrice: Double?) {
        if (title.isBlank()) return
        viewModelScope.launch { repo.addWantAlert(title, platform, targetPrice) }
    }

    fun addBought(title: String, platform: String, purchasePrice: Double) {
        if (title.isBlank() || platform.isBlank() || purchasePrice <= 0) return
        viewModelScope.launch { repo.addBoughtAlert(title, platform, purchasePrice, System.currentTimeMillis()) }
    }

    fun stop(id: Long) = viewModelScope.launch { repo.setAlertStatus(id, AlertStatus.STOPPED) }
    fun archive(id: Long) = viewModelScope.launch { repo.setAlertStatus(id, AlertStatus.DONE) }
    fun reactivate(id: Long) = viewModelScope.launch { repo.setAlertStatus(id, AlertStatus.ACTIVE) }
    fun delete(id: Long) = viewModelScope.launch { repo.deleteAlert(id) }

    /** 立即查价:跟 MainActivity.onResume 同路径,batchCheck + 发本地通知。 */
    fun refreshAll() {
        if (_refreshing.value) return
        _refreshing.value = true
        viewModelScope.launch {
            try {
                val triggered = withContext(Dispatchers.IO) { repo.batchCheckAlerts() }
                if (triggered.isNotEmpty()) AlertNotifier.notifyTriggered(getApplication(), triggered)
            } catch (_: Exception) {
            } finally {
                _refreshing.value = false
            }
        }
    }
}
