package com.fabledsword.minstrel.cache.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface CachedQuarantineDao {
    /** Newest-first listing for the Quarantine screen. */
    @Query("SELECT * FROM cached_quarantine_mine ORDER BY createdAt DESC")
    fun observeAll(): Flow<List<CachedQuarantineEntity>>

    /** Just the IDs — feed-filtering code reads this to hide tracks. */
    @Query("SELECT trackId FROM cached_quarantine_mine")
    fun observeFlaggedTrackIds(): Flow<List<String>>

    @Query(
        "SELECT EXISTS(SELECT 1 FROM cached_quarantine_mine WHERE trackId = :trackId)",
    )
    fun observeIsHidden(trackId: String): Flow<Boolean>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsert(row: CachedQuarantineEntity)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun upsertAll(rows: List<CachedQuarantineEntity>)

    @Query("DELETE FROM cached_quarantine_mine WHERE trackId = :trackId")
    suspend fun deleteByTrackId(trackId: String)

    @Query("DELETE FROM cached_quarantine_mine WHERE trackId IN (:trackIds)")
    suspend fun deleteByTrackIds(trackIds: List<String>)

    @Query("DELETE FROM cached_quarantine_mine")
    suspend fun clear()

    /**
     * Atomic full-replace from the server snapshot — one transaction so
     * the `observeAll()` watcher sees a single merged emission, not a
     * delete-then-insert flicker. Mirrors Flutter's MyQuarantineController
     * `_refreshFromServer` transaction.
     */
    @Transaction
    suspend fun replaceAll(rows: List<CachedQuarantineEntity>) {
        clear()
        upsertAll(rows)
    }
}
