package ru.fincode.tsudesk.core.config.data

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import ru.fincode.tsudesk.core.common.model.DataResult
import ru.fincode.tsudesk.core.config.data.datasource.ConfigRemoteDataSource
import ru.fincode.tsudesk.core.config.domain.ConfigRepository
import ru.fincode.tsudesk.core.config.domain.model.AppConfig
import ru.fincode.tsudesk.core.network.model.NetworkResult
import javax.inject.Inject

class ConfigRepositoryImpl @Inject constructor(
    private val remoteDataSource: ConfigRemoteDataSource
) : ConfigRepository {

    private val defaultConfig = AppConfig()

    override suspend fun fetchConfig(): DataResult<AppConfig> {
        return when (val res = remoteDataSource.load()) {
            is NetworkResult.Success -> {
                val dto = res.data
                DataResult.Data(
                    data = AppConfig(
                        newsEnabled = dto.newsEnabled ?: defaultConfig.newsEnabled,
                        scheduleEnabled = dto.scheduleEnabled ?: defaultConfig.scheduleEnabled,
                        gradesEnabled = dto.gradesEnabled ?: defaultConfig.gradesEnabled
                    ),
                    refreshedFromNetwork = true
                )
            }

            is NetworkResult.Error -> {
                DataResult.Error(
                    error = res.error.toAppError(), data = defaultConfig
                )
            }
        }
    }


    override fun getConfig(): Flow<DataResult<AppConfig>> = flow {
        when (val result = remoteDataSource.load()) {
            is NetworkResult.Success -> {
                val dto = result.data
                val appConfig = AppConfig(
                    newsEnabled = dto.newsEnabled ?: defaultConfig.newsEnabled,
                    scheduleEnabled = dto.scheduleEnabled ?: defaultConfig.scheduleEnabled,
                    gradesEnabled = dto.gradesEnabled ?: defaultConfig.gradesEnabled
                )
                emit(DataResult.Data(data = appConfig, refreshedFromNetwork = true))
            }

            is NetworkResult.Error -> {
                emit(
                    DataResult.Error(
                        error = result.error.toAppError(),
                        data = defaultConfig
                    )
                )
            }
        }
    }
}
