package lu.rewardflow.terminal.data.db.dao

import androidx.room.*
import kotlinx.coroutines.flow.Flow
import lu.rewardflow.terminal.data.db.entity.PendingTransaction

@Dao
interface PendingTransactionDao {

    @Insert
    suspend fun insert(transaction: PendingTransaction): Long

    @Query("SELECT * FROM pending_transactions WHERE status = 'pending' ORDER BY createdAt ASC")
    suspend fun getPending(): List<PendingTransaction>

    /** Reactive count for the PIN-screen badge — re-emits whenever the
     *  queue changes (insert / update / delete). */
    @Query("SELECT COUNT(*) FROM pending_transactions WHERE status = 'pending'")
    fun getPendingCount(): Flow<Int>

    @Update
    suspend fun update(transaction: PendingTransaction)

    @Query("DELETE FROM pending_transactions WHERE status = 'synced'")
    suspend fun deleteSynced()

    @Query("UPDATE pending_transactions SET status = 'failed', lastError = :error, retryCount = retryCount + 1 WHERE id = :id")
    suspend fun markFailed(id: Long, error: String)

    @Query("UPDATE pending_transactions SET status = 'synced' WHERE id = :id")
    suspend fun markSynced(id: Long)
}
