package com.radiola.data.repository

import com.radiola.data.local.AppDatabase
import com.radiola.data.local.entity.TrackHistoryEntity
import com.radiola.domain.model.Track
import com.radiola.domain.repository.TrackHistoryRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

class TrackHistoryRepositoryImpl @Inject constructor(
    private val db: AppDatabase
) : TrackHistoryRepository {

    override fun getHistory(): Flow<List<Track>> {
        return db.trackHistoryDao().getAll().map { list ->
            list.map { it.toDomain() }
        }
    }

    override suspend fun addTrack(track: Track) {
        val entity = TrackHistoryEntity(
            artist = track.artist,
            song = track.song,
            stationName = track.stationName,
            coverUrl = track.coverUrl,
            timestamp = System.currentTimeMillis()
        )
        db.trackHistoryDao().insert(entity)
        db.trackHistoryDao().cleanupOld()
    }

    override suspend fun removeTrack(track: Track) {
        // Requires lookup by composite key; simplified for now
    }

    override suspend fun searchHistory(query: String): List<Track> {
        return db.trackHistoryDao().search(query).map { it.toDomain() }
    }

    private fun TrackHistoryEntity.toDomain(): Track = Track(
        artist = artist,
        song = song,
        coverUrl = coverUrl,
        stationName = stationName
    )
}
