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.CachedArtistEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface CachedArtistDao {
    @Query("SELECT * FROM cached_artists ORDER BY sortName COLLATE NOCASE ASC")
    fun observeAll(): Flow<List<CachedArtistEntity>>

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

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

    @Query(
        "SELECT * FROM cached_artists " +
            "WHERE name LIKE '%' || :q || '%' COLLATE NOCASE " +
            "ORDER BY sortName COLLATE NOCASE ASC " +
            "LIMIT :limit",
    )
    suspend fun searchByName(q: String, limit: Int): List<CachedArtistEntity>

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

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

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