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

@Dao
interface CachedPlaylistTrackDao {
    @Query(
        "SELECT * FROM cached_playlist_tracks " +
            "WHERE playlistId = :playlistId ORDER BY position ASC",
    )
    fun observeByPlaylist(playlistId: String): Flow<List<CachedPlaylistTrackEntity>>

    @Query(
        "SELECT * FROM cached_playlist_tracks " +
            "WHERE playlistId = :playlistId ORDER BY position ASC",
    )
    suspend fun getByPlaylist(playlistId: String): List<CachedPlaylistTrackEntity>

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

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertOrIgnore(row: CachedPlaylistTrackEntity)

    /**
     * Highest existing position for [playlistId], or null if the
     * playlist has no rows. Used by appendTrack to assign the next
     * position before the optimistic Room write.
     */
    @Query("SELECT MAX(position) FROM cached_playlist_tracks WHERE playlistId = :playlistId")
    suspend fun maxPosition(playlistId: String): Int?

    /** Replace-all pattern for a playlist; called after a sync delta lands. */
    @Query("DELETE FROM cached_playlist_tracks WHERE playlistId = :playlistId")
    suspend fun deleteByPlaylist(playlistId: String)

    @Query(
        "DELETE FROM cached_playlist_tracks " +
            "WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
    )
    suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List<String>)
}
