/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.player

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.runicgateway.app.data.api.dto.CharProfileDto
import com.runicgateway.app.data.repository.PlayerShardRepository
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.ui.navigation.Routes
import com.runicgateway.app.ui.toUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * A single character sheet (PLAN.md §6.3), read from `/player/shard/char/:serial`
 * for a character on one of the caller's linked accounts (ownership-checked
 * server-side). A `503` renders as offline/retry, a `403` as not-found (§7).
 * Text-only presentation for v1.
 */
@HiltViewModel
class CharacterViewModel @Inject constructor(
    private val repository: PlayerShardRepository,
    savedStateHandle: SavedStateHandle,
) : ViewModel() {

    private val serial: String = savedStateHandle.get<String>(Routes.Args.SERIAL).orEmpty()

    private val _state = MutableStateFlow<UiState<CharProfileDto>>(UiState.Loading)
    val state: StateFlow<UiState<CharProfileDto>> = _state.asStateFlow()

    init {
        load()
    }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = repository.char(serial).toUiState()
        }
    }
}
