package com.zaojiao.app.feat.home.personal

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zaojiao.app.core.auth.data.AuthRepository
import com.zaojiao.app.core.auth.utils.AuthState
import com.zaojiao.app.data.repo.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class HomePersonalViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository,
) : ViewModel() {

    val userUiState: StateFlow<HomePersonalUserUiState> =
        combine(authRepository.state, userRepository.user) { auth, user ->
            when (auth) {
                AuthState.IN -> {
                    HomePersonalUserUiState(
                        name = user?.nickName ?: "逻辑狗",
                        avatar = user?.avatarUrl,
                    )
                }

                AuthState.OUT -> {
                    HomePersonalUserUiState.Login
                }
            }
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomePersonalUserUiState.None,
        )

    val interactiveUiState: StateFlow<HomePersonalInteractiveUiState> =
        combine(authRepository.state, userRepository.interactiveCount) { auth, interactive ->
            when (auth) {
                AuthState.IN -> {
                    HomePersonalInteractiveUiState(
                        followerCount = interactive.followerCount,
                        fansCount = interactive.fansCount,
                        likeCount = interactive.likeCount,
                        collectionCount = interactive.collectionCount,
                    )
                }

                AuthState.OUT -> {
                    HomePersonalInteractiveUiState()
                }
            }
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomePersonalInteractiveUiState(),
        )
}