package ru.myitschool.work.data.repo

import dagger.Lazy
import dagger.Reusable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import ru.myitschool.work.data.mapper.UserInfoMapper
import ru.myitschool.work.data.source.AccountNetworkDataSource
import ru.myitschool.work.domain.profile.entities.UserInfoEntity
import ru.myitschool.work.domain.profile.repo.UserInfoRepository
import javax.inject.Inject

@Reusable
class AccountRepositoryImpl @Inject constructor(
    private val accountNetworkDataSource: AccountNetworkDataSource,
    private val userInfoMapper: Lazy<UserInfoMapper>,
): UserInfoRepository {
    override suspend fun getInfo(username: String): Result<UserInfoEntity> {
        return withContext(Dispatchers.IO) {
            accountNetworkDataSource.getInfo(username).fold(
                onSuccess = { value -> userInfoMapper.get().invoke(value) },
                onFailure = { error -> Result.failure(error) }
            )
        }
    }

    override suspend fun openByQr(username: String, content: String): Result<Unit> {
        return withContext(Dispatchers.IO) {
            accountNetworkDataSource.openByQr(username, content)
        }
    }
}