package com.zaojiao.app.data.repo.impl

import com.zaojiao.app.core.auth.data.LocalAuthData
import com.zaojiao.app.core.auth.utils.AuthState
import com.zaojiao.app.core.common.remote.di.ApplicationScope
import com.zaojiao.app.core.common.state.DataState
import com.zaojiao.app.data.local.user.LocalUserData
import com.zaojiao.app.data.model.interactive.InteractiveCountModel
import com.zaojiao.app.data.model.user.UserModel
import com.zaojiao.app.data.remote.RemoteUserData
import com.zaojiao.app.data.repo.UserRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


class UserRepositoryImpl @Inject constructor(
    private val localAuthData: LocalAuthData,
    private val localUserData: LocalUserData,
    private val remoteUserData: RemoteUserData,
    @ApplicationScope private val coroutineScope: CoroutineScope,
) : UserRepository {
    override val user: Flow<UserModel?> = localUserData.user

    private val _interactiveCount = MutableStateFlow(InteractiveCountModel())
    override val interactiveCount: Flow<InteractiveCountModel> get() = _interactiveCount

    private val _phoneNumber = MutableStateFlow<String?>(null)
    override val phoneNumber: Flow<String?> get() = _phoneNumber

    private val _wechatState = MutableStateFlow(false)
    override val wechatState: Flow<Boolean> get() = _wechatState

    init {
        coroutineScope.launch {
            localAuthData.state.collect {
                when (it) {
                    AuthState.IN -> fetchData()
                    AuthState.OUT -> cleanData()
                }
            }
        }
    }

    override suspend fun fetchData() {
        remoteUserData.getUserInfo().apply {
            when (this) {
                is DataState.Failure -> {}
                is DataState.Success -> {
                    data?.apply {
                        localUserData.updateUser(this)
                    }
                }
            }
        }

        remoteUserData.getUserInactive().apply {
            if (this is DataState.Success) {
                data?.apply { _interactiveCount.emit(this) }
            }
        }
    }

    private suspend fun cleanData() {
        deleteUser()
        _interactiveCount.emit(InteractiveCountModel())
    }

    override suspend fun updateUser(userModel: UserModel) {
        TODO("Not yet implemented")
    }


    override suspend fun deleteUser() {
        localUserData.deleteUser()
    }
}