package com.rssuper.database.daos

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.rssuper.database.entities.SearchHistoryEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface SearchHistoryDao {
    @Query("SELECT * FROM search_history ORDER BY timestamp DESC")
    fun getAllSearchHistory(): Flow<List<SearchHistoryEntity>>
    
    @Query("SELECT * FROM search_history WHERE id = :id")
    suspend fun getSearchHistoryById(id: String): SearchHistoryEntity?
    
    @Query("SELECT * FROM search_history WHERE query LIKE '%' || :query || '%' ORDER BY timestamp DESC")
    fun searchHistory(query: String): Flow<List<SearchHistoryEntity>>
    
    @Query("SELECT * FROM search_history ORDER BY timestamp DESC LIMIT :limit")
    fun getRecentSearches(limit: Int): Flow<List<SearchHistoryEntity>>
    
    @Query("SELECT COUNT(*) FROM search_history")
    fun getSearchHistoryCount(): Flow<Int>
    
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertSearchHistory(search: SearchHistoryEntity): Long
    
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertSearchHistories(searches: List<SearchHistoryEntity>): List<Long>
    
    @Update
    suspend fun updateSearchHistory(search: SearchHistoryEntity): Int
    
    @Delete
    suspend fun deleteSearchHistory(search: SearchHistoryEntity): Int
    
    @Query("DELETE FROM search_history WHERE id = :id")
    suspend fun deleteSearchHistoryById(id: String): Int
    
    @Query("DELETE FROM search_history")
    suspend fun deleteAllSearchHistory(): Int
    
    @Query("DELETE FROM search_history WHERE timestamp < :timestamp")
    suspend fun deleteSearchHistoryOlderThan(timestamp: Long): Int
}
