package com.zaojiao.app.data.domain

import android.content.Context
import com.zaojiao.app.data.repo.BabyRepository
import com.zaojiao.app.data.repo.LoginRepository
import com.zaojiao.app.data.repo.LoginState
import com.zaojiao.app.data.repo.UserRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AccountUseCase @Inject constructor(
    private val loginRepository: LoginRepository,
    private val userRepository: UserRepository,
    private val babyRepository: BabyRepository,
    @ApplicationContext private val context: Context,
) {
    val appState: Flow<LoginState> = flow {
        emit(LoginState.OUT)

        loginRepository.state.onEach {
            try {
                if (it == LoginState.IN) {
                    userRepository.getUser()
                    babyRepository.getBaby()
                } else {
                    userRepository.deleteUser()
                    babyRepository.deleteAllBaby()
                }
                emit(LoginState.IN)
            } catch (throwable: Throwable) {
                emit(LoginState.OUT)
            }
        }
    }

    operator fun invoke() {

    }
}