package com.radiola.data.repository

import com.radiola.data.local.AppDatabase
import com.radiola.data.local.entity.StationEntity
import com.radiola.domain.model.Station
import com.radiola.domain.repository.FavoritesRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class FavoritesRepositoryImpl @Inject constructor(
    private val db: AppDatabase
) : FavoritesRepository {

    override fun getFavorites(): Flow<List<Station>> {
        return db.stationDao().getFavorites().map { list ->
            list.map { it.toDomain() }
        }
    }

    override fun getFavoriteIds(): Flow<Set<Int>> {
        return db.stationDao().getFavoriteIds().map { it.toSet() }
    }

    override suspend fun addFavorite(station: Station) {
        db.stationDao().setFavorite(station.id, true)
    }

    override suspend fun addFavorite(stationId: Int) {
        db.stationDao().setFavorite(stationId, true)
    }

    override suspend fun removeFavorite(stationId: Int) {
        db.stationDao().setFavorite(stationId, false)
    }

    override fun isFavorite(stationId: Int): Flow<Boolean> {
        return db.stationDao().isFavorite(stationId)
    }

    override suspend fun reorderFavorites(orderedIds: List<Int>) {
        // TODO: implement drag-sort reordering
    }

    private fun StationEntity.toDomain(): Station = Station(
        id = id,
        name = name,
        prefix = prefix,
        streamUrl = streamUrl,
        coverUrl = coverUrl,
        genre = genre,
        tags = tags.split(",").filter { it.isNotBlank() },
        sortOrder = sortOrder,
        source = source
    )
}
