package com.jishisongfu.duobibi.data.db

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow

@Dao
interface PriceAlertDao {

    @Insert
    suspend fun insert(item: PriceAlert): Long

    @Update
    suspend fun update(item: PriceAlert)

    @Query("SELECT * FROM price_alert ORDER BY createdAt DESC")
    fun observeAll(): Flow<List<PriceAlert>>

    @Query("SELECT * FROM price_alert WHERE mode = :mode ORDER BY createdAt DESC")
    fun observeByMode(mode: String): Flow<List<PriceAlert>>

    /** 后台批量查价只跑 active 的 */
    @Query("SELECT * FROM price_alert WHERE status = 'active' ORDER BY createdAt DESC")
    suspend fun getActive(): List<PriceAlert>

    @Query("SELECT * FROM price_alert WHERE id = :id")
    suspend fun byId(id: Long): PriceAlert?

    @Query("DELETE FROM price_alert WHERE id = :id")
    suspend fun delete(id: Long)

    @Query("UPDATE price_alert SET status = :status WHERE id = :id")
    suspend fun setStatus(id: Long, status: String)

    @Query("SELECT COUNT(*) FROM price_alert WHERE status = 'active'")
    fun observeActiveCount(): Flow<Int>

    /** active 且已到价(lastSavings>0)条数 — 雷达 Tab 角标 / 首屏提示 */
    @Query("""
        SELECT COUNT(*) FROM price_alert
        WHERE status = 'active' AND lastSavings IS NOT NULL AND lastSavings > 0
    """)
    fun observeReadyCount(): Flow<Int>

    /** 后台查完批量更新差价字段,不动基础字段 */
    @Query("""
        UPDATE price_alert
        SET lastCheckedAt = :ts, lastCurrentPrice = :currentPrice,
            lastTrend = :trend, lastSavings = :savings
        WHERE id = :id
    """)
    suspend fun updateCheckResult(id: Long, ts: Long, currentPrice: Double, trend: String, savings: Double)

    @Query("DELETE FROM price_alert WHERE isDemo = 1")
    suspend fun deleteDemo()

    @Query("DELETE FROM price_alert")
    suspend fun deleteAll()
}
