package com.radiola.data.local.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.radiola.data.local.entity.StationEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface StationDao {

    @Query("SELECT * FROM stations ORDER BY sortOrder ASC")
    fun getAll(): Flow<List<StationEntity>>

    @Query("SELECT * FROM stations WHERE isFavorite = 1 ORDER BY sortOrder ASC")
    fun getFavorites(): Flow<List<StationEntity>>

    @Query("SELECT * FROM stations WHERE id = :id")
    fun getById(id: Int): Flow<StationEntity?>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(stations: List<StationEntity>)

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

    @Update
    suspend fun update(station: StationEntity)

    @Query("UPDATE stations SET isFavorite = :isFavorite WHERE id = :id")
    suspend fun setFavorite(id: Int, isFavorite: Boolean)

    @Query("SELECT isFavorite FROM stations WHERE id = :id")
    fun isFavorite(id: Int): Flow<Boolean>

    @Query("SELECT id FROM stations WHERE isFavorite = 1")
    fun getFavoriteIds(): Flow<List<Int>>

    // Разовое чтение id избранного — чтобы при пересоздании каталога (refreshStations)
    // не потерять отметки «избранное» (insertAll = REPLACE затирает строки).
    @Query("SELECT id FROM stations WHERE isFavorite = 1")
    suspend fun getFavoriteIdsOnce(): List<Int>

    // Разовое чтение станции по id — используется в сервисе будильника.
    @Query("SELECT * FROM stations WHERE id = :id")
    suspend fun getByIdOnce(id: Int): StationEntity?
}
