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

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

@Dao
interface CachedTrackDao {
    @Query(
        "SELECT * FROM cached_tracks " +
            "WHERE albumId = :albumId ORDER BY discNumber ASC, trackNumber ASC",
    )
    fun observeByAlbum(albumId: String): Flow<List<CachedTrackEntity>>

    @Query("SELECT * FROM cached_tracks WHERE id = :id")
    suspend fun getById(id: String): CachedTrackEntity?

    @Query("SELECT * FROM cached_tracks WHERE id = :id")
    fun observeById(id: String): Flow<CachedTrackEntity?>

    @Query("SELECT * FROM cached_tracks WHERE id IN (:ids)")
    suspend fun getByIds(ids: List<String>): List<CachedTrackEntity>

    @Query(
        "SELECT * FROM cached_tracks " +
            "WHERE title LIKE '%' || :q || '%' COLLATE NOCASE " +
            "ORDER BY title COLLATE NOCASE ASC " +
            "LIMIT :limit",
    )
    suspend fun searchByTitle(q: String, limit: Int): List<CachedTrackEntity>

    @Query("SELECT id FROM cached_tracks WHERE fetchedAt < :before LIMIT :limit")
    suspend fun idsStaleBefore(before: Long, limit: Int): List<String>

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

    @Query("DELETE FROM cached_tracks WHERE id IN (:ids)")
    suspend fun deleteByIds(ids: List<String>)
}
