package ru.myitschool.work.data.repo

import dagger.Reusable
import ru.myitschool.work.data.source.AuthorizationNetworkDataSource
import ru.myitschool.work.data.source.AuthorizationStorageDataSource
import ru.myitschool.work.domain.auth.repo.AuthorizationRepository
import javax.inject.Inject
import dagger.Lazy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.withContext

@Reusable
class AuthorizationRepositoryImpl @Inject constructor(
    private val authorizationStorageDataSource: Lazy<AuthorizationStorageDataSource>,
    private val authorizationNetworkDataSource: Lazy<AuthorizationNetworkDataSource>,
): AuthorizationRepository {

    override suspend fun login(username: String): Result<Unit> {
        return withContext(Dispatchers.IO) {
            authorizationNetworkDataSource.get().checkLogin(username)
                .onSuccess {
                    authorizationStorageDataSource.get().updateLogin(username)
                }
        }
    }

    override suspend fun logout() {
        authorizationStorageDataSource.get().updateLogin(null)
    }

    override suspend fun getLogin(): Result<String> {
        val result = authorizationStorageDataSource.get().login.firstOrNull()
        return if (result == null) {
            Result.failure(Exception("Not authorize"))
        } else {
            Result.success(result)
        }
    }
}