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.DiagnosticEventEntity

@Dao
interface DiagnosticEventDao {
    @Insert
    suspend fun insert(row: DiagnosticEventEntity): Long

    /** FIFO drain order so the uploader sends oldest-first. */
    @Query("SELECT * FROM diagnostic_events ORDER BY id ASC LIMIT :limit")
    suspend fun takeBatch(limit: Int): List<DiagnosticEventEntity>

    @Query("SELECT COUNT(*) FROM diagnostic_events")
    suspend fun count(): Int

    @Query("DELETE FROM diagnostic_events WHERE id IN (:ids)")
    suspend fun deleteByIds(ids: List<Long>)

    /**
     * Ring-buffer trim: drop the oldest rows beyond [keep]. Called after
     * insert so a long offline stretch can't grow the buffer unbounded.
     */
    @Query(
        "DELETE FROM diagnostic_events WHERE id NOT IN " +
            "(SELECT id FROM diagnostic_events ORDER BY id DESC LIMIT :keep)",
    )
    suspend fun trimToNewest(keep: Int)

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