package xyz.cottongin.radio247.data.db

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import xyz.cottongin.radio247.data.model.Station
import kotlinx.coroutines.flow.Flow

@Dao
interface StationDao {
    @Query("SELECT * FROM stations ORDER BY starred DESC, sortOrder ASC")
    fun getAllStations(): Flow<List<Station>>

    @Query("SELECT * FROM stations WHERE playlistId = :playlistId AND isHidden = 0 ORDER BY starred DESC, sortOrder ASC")
    fun getStationsByPlaylist(playlistId: Long): Flow<List<Station>>

    @Query("SELECT * FROM stations WHERE playlistId IS NULL AND isHidden = 0 ORDER BY starred DESC, sortOrder ASC")
    fun getUnsortedStations(): Flow<List<Station>>

    @Query("SELECT * FROM stations WHERE playlistId = :playlistId AND isHidden = 1 ORDER BY sortOrder ASC")
    fun getHiddenStationsByPlaylist(playlistId: Long): Flow<List<Station>>

    @Query("SELECT * FROM stations WHERE playlistId IS NULL AND isHidden = 1 ORDER BY sortOrder ASC")
    fun getHiddenUnsortedStations(): Flow<List<Station>>

    @Query("SELECT COUNT(*) FROM stations WHERE playlistId = :playlistId AND isHidden = 1")
    fun getHiddenCountByPlaylist(playlistId: Long): Flow<Int>

    @Query("SELECT COUNT(*) FROM stations WHERE playlistId IS NULL AND isHidden = 1")
    fun getHiddenUnsortedCount(): Flow<Int>

    @Query("SELECT * FROM stations WHERE id = :id")
    suspend fun getStationById(id: Long): Station?

    @Insert
    suspend fun insert(station: Station): Long

    @Update
    suspend fun update(station: Station)

    @Delete
    suspend fun delete(station: Station)

    @Query("UPDATE stations SET sortOrder = :sortOrder WHERE id = :id")
    suspend fun updateSortOrder(id: Long, sortOrder: Int)

    @Query("UPDATE stations SET starred = :starred WHERE id = :id")
    suspend fun toggleStarred(id: Long, starred: Boolean)

    @Query("UPDATE stations SET isHidden = :isHidden WHERE id = :id")
    suspend fun toggleHidden(id: Long, isHidden: Boolean)

    @Query("UPDATE stations SET listenerCount = :count WHERE id = :id")
    suspend fun updateListenerCount(id: Long, count: Int)
}
