package com.radiola.data.repository

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

class RecognizedTrackRepositoryImpl @Inject constructor(
    private val db: AppDatabase
) : RecognizedTrackRepository {

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

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

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