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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
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.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

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

    init {
        viewModelScope.launch {
            userRepository.getUser()
        }
    }

    val userUiState: StateFlow<HomePersonalUserUiState> = userRepository.user
        .map {
            HomePersonalUserUiState(
                name = it?.nickName ?: "逻辑狗",
                avatar = it?.avatarUrl,
            )
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomePersonalUserUiState(
                name = "逻辑狗",
                avatar = null,
            )
        )
}