package ru.myitschool.work.data.source

import android.accounts.NetworkErrorException
import dagger.Reusable
import retrofit2.Retrofit
import javax.inject.Inject

@Reusable
class AuthorizationNetworkDataSource @Inject constructor(
    private val retrofit: Retrofit
) {
    private val api by lazy {
        retrofit.create(AuthorizationApi::class.java)
    }

    suspend fun checkLogin(username: String): Result<Unit> {
        return kotlin.runCatching { api.checkLogin(username = username) }.fold(
            onSuccess = { response ->
                when (response.code()) {
                    200 -> Result.success(Unit)
                    else -> Result.failure(NetworkErrorException("Error ${response.code()}"))
                }
            },
            onFailure = { error -> Result.failure(error) }
        )
    }
}