package com.soundapp.soundgags.datame

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query

@Dao
interface ReflectionDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(reflection: Reflection): Long
    @Delete
    suspend fun delete(reflection: Reflection): Int
    @Query("SELECT * FROM reflection")
    suspend fun selectAll(): List<Reflection>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertAll(infos: List<Reflection>): List<Long>

    //使用索引优化查询
    @Query("SELECT * FROM reflection WHERE isLike = 1 ORDER BY id ASC")
    fun getAllLike(): List<Reflection>

    @Query("SELECT * FROM reflection WHERE isCustomization = 1 ORDER BY id ASC")
    fun getAllCustomization(): List<Reflection>

    // 高效的随机查询（使用SQLite的随机函数）
    @Query("""
        SELECT * FROM reflection 
        WHERE isCustomization = 0 
        ORDER BY RANDOM() 
        LIMIT 11
    """)
    suspend fun getMoreEfficient(): List<Reflection>

    // 使用EXISTS进行存在性检查（更高效）
    @Query("SELECT EXISTS(SELECT 1 FROM reflection WHERE name = :name AND isLike = 1)")
    suspend fun checkLikeExists(name: String): Boolean

    @Query("SELECT EXISTS(SELECT 1 FROM reflection WHERE name = :name)")
    suspend fun checkNameExists(name: String): Boolean


    @Query("UPDATE reflection SET isLike = :isLike WHERE name = :name")
    suspend fun updateLikeStatus(name: String, isLike: Boolean): Int


    @Query("UPDATE reflection SET isLike = 0 WHERE name = :name")
    suspend fun removeLike(name: String)
}