package com.jishisongfu.duobibi.data.db

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

@Dao
interface PriceRecordDao {

    @Insert
    suspend fun insert(record: PriceRecord): Long

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

    @Query("SELECT * FROM price_record WHERE title LIKE '%' || :q || '%' ORDER BY createdAt DESC")
    fun search(q: String): Flow<List<PriceRecord>>

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

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

    @Query("UPDATE price_record SET clusterId = :newClusterId WHERE id = :recordId")
    suspend fun moveRecord(recordId: Long, newClusterId: Long)

    @Query("SELECT COUNT(*) FROM price_record WHERE clusterId = :clusterId")
    suspend fun countInCluster(clusterId: Long): Int

    @Query("DELETE FROM price_record WHERE clusterId = :clusterId")
    suspend fun deleteByCluster(clusterId: Long)

    @Query("SELECT * FROM price_record WHERE clusterId = :clusterId ORDER BY createdAt DESC")
    fun observeByCluster(clusterId: Long): Flow<List<PriceRecord>>

    @Query("SELECT * FROM price_record WHERE clusterId = :clusterId ORDER BY createdAt DESC")
    suspend fun byCluster(clusterId: Long): List<PriceRecord>

    @Query("SELECT MIN(price) FROM price_record WHERE clusterId = :clusterId")
    suspend fun minPriceInCluster(clusterId: Long): Double?

    @Query("DELETE FROM price_record")
    suspend fun deleteAll()

    /** 清除"示例数据"占审用条目。仅删 isDemo=1 的,真实用户数据不受影响。 */
    @Query("DELETE FROM price_record WHERE isDemo = 1")
    suspend fun deleteDemo()
}
