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

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.datetime.Instant

@Dao
interface CachedMutationDao {
    /** Pending count for the offline-indicator badge. */
    @Query("SELECT COUNT(*) FROM cached_mutations")
    fun observePendingCount(): Flow<Int>

    /** FIFO drain order so the replayer processes oldest first. */
    @Query("SELECT * FROM cached_mutations ORDER BY id ASC")
    suspend fun getAll(): List<CachedMutationEntity>

    @Insert
    suspend fun insert(row: CachedMutationEntity): Long

    @Query(
        "UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " +
            "WHERE id = :id",
    )
    suspend fun recordAttempt(id: Long, at: Instant)

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

    @Query("DELETE FROM cached_mutations")
    suspend fun clear()
}
