package com.jishisongfu.duobibi.ui.mine

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.db.AlertStatus
import com.jishisongfu.duobibi.data.repo.PriceRepository
import com.jishisongfu.duobibi.util.DemoDataSeeder
import com.jishisongfu.duobibi.util.StatsCalculator
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * "我的"屏顶部 hero 卡里展示的 4 项本机统计。全部由本机 Room 数据实时计算 ——
 * 不放任何虚构数字,审核员对得上(空库时 4 项都是 0)。
 */
data class MineStats(
    val totalProducts: Int,
    val totalRecords: Int,
    val activeAlerts: Int,
    val totalSaved: Double,
)

@HiltViewModel
class MineViewModel @Inject constructor(
    app: Application,
    private val repo: PriceRepository,
) : AndroidViewModel(app) {

    /** 三流合并:商品簇 + 价格记录 + 降价雷达 → MineStats。初始值给全零,避免首帧 null 闪烁。 */
    val stats: StateFlow<MineStats> = combine(
        repo.observeAllClusters(),
        repo.observeAllRecords(),
        repo.observeAllAlerts(),
    ) { clusters, records, alerts ->
        val overall = StatsCalculator.computeOverall(clusters, records)
        MineStats(
            totalProducts = overall.totalProducts,
            totalRecords = overall.totalRecords,
            activeAlerts = alerts.count { it.status == AlertStatus.ACTIVE },
            totalSaved = overall.totalSaved,
        )
    }.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5_000),
        MineStats(0, 0, 0, 0.0),
    )

    fun clearDemo(onDone: () -> Unit) {
        viewModelScope.launch {
            DemoDataSeeder.clearAndUnseed(getApplication(), repo)
            onDone()
        }
    }

    fun clearAll(onDone: () -> Unit) {
        viewModelScope.launch {
            repo.deleteAll()
            onDone()
        }
    }
}
