package com.seven.ikar.kotlin.feature.profile

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.model.UserSummaryDto
import com.seven.ikar.kotlin.core.network.ServerConfig
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class PeerProfileUiState(
    val userId: String,
    val accessToken: String? = null,
    val user: UserSummaryDto? = null,
    val avatarUrl: String? = null,
    val isLoading: Boolean = false,
    val errorMessage: String? = null
)

class PeerProfileViewModel(
    private val container: AppContainer,
    private val userId: String
) : ViewModel() {
    private val _uiState = MutableStateFlow(PeerProfileUiState(userId = userId))
    val uiState: StateFlow<PeerProfileUiState> = _uiState.asStateFlow()

    init {
        refresh()
    }

    fun refresh() {
        if (container.sessionStore.read() == null) return
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            runCatching {
                container.executeAuthorized { session ->
                    session.accessToken to container.apiClient.getUser(session.accessToken, userId)
                }
            }.onSuccess { (accessToken, user) ->
                _uiState.value = _uiState.value.copy(
                    accessToken = accessToken,
                    user = user,
                    avatarUrl = ServerConfig.normalizeMediaUrl(user.avatarPath),
                    isLoading = false,
                    errorMessage = null
                )
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = error.message)
            }
        }
    }
}
