package com.radiola.data.repository

import com.radiola.data.local.TokenDataStore
import com.radiola.data.remote.RadiolaApi
import com.radiola.domain.repository.SyncRepository
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class SyncRepositoryImpl @Inject constructor(
    private val api: RadiolaApi,
    private val tokenDataStore: TokenDataStore
) : SyncRepository {

    private fun isLoggedIn(): Boolean = tokenDataStore.currentToken != null

    override suspend fun pushFavorite(stationId: Int): Result<Unit> {
        if (!isLoggedIn()) return Result.success(Unit)
        return try {
            api.addFavorite(stationId.toString())
            Result.success(Unit)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun removeFavorite(stationId: Int): Result<Unit> {
        if (!isLoggedIn()) return Result.success(Unit)
        return try {
            api.removeFavorite(stationId.toString())
            Result.success(Unit)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun pushHistory(stationId: Int): Result<Unit> {
        if (!isLoggedIn()) return Result.success(Unit)
        return try {
            api.addHistory(stationId.toString())
            Result.success(Unit)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun fetchRemoteFavorites(): Result<List<Int>> {
        if (!isLoggedIn()) return Result.success(emptyList())
        return try {
            val stations = api.getFavorites()
            Result.success(stations.map { it.stationId })
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    override suspend fun fetchRemoteHistory(): Result<List<Int>> {
        if (!isLoggedIn()) return Result.success(emptyList())
        return try {
            val response = api.getHistory()
            Result.success(response.items.map { it.stationId })
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
