package de.tsschulz.tt_tagebuch.shared.state

import de.tsschulz.tt_tagebuch.shared.api.OfficialTournamentsApi
import de.tsschulz.tt_tagebuch.shared.api.models.OfficialParticipationBucketDto
import de.tsschulz.tt_tagebuch.shared.api.models.OfficialTournamentListRowDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

data class OfficialTournamentsReadState(
    val tournaments: List<OfficialTournamentListRowDto> = emptyList(),
    val participationBuckets: List<OfficialParticipationBucketDto> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
)

class OfficialTournamentsReadManager(
    private val api: OfficialTournamentsApi,
) {
    private val _state = MutableStateFlow(OfficialTournamentsReadState())
    val state: StateFlow<OfficialTournamentsReadState> = _state.asStateFlow()

    fun clear() {
        _state.value = OfficialTournamentsReadState()
    }

    suspend fun load(clubId: Int) {
        _state.update { it.copy(isLoading = true, error = null) }
        try {
            val list = api.listForClub(clubId)
            val summary = api.listParticipationSummary(clubId)
            _state.update {
                it.copy(
                    tournaments = list,
                    participationBuckets = summary,
                    isLoading = false,
                    error = null,
                )
            }
        } catch (t: Throwable) {
            _state.update {
                it.copy(
                    isLoading = false,
                    error = t.toUserMessage("Offizielle Turniere konnten nicht geladen werden"),
                )
            }
        }
    }

    suspend fun fetchParticipationSummary(clubId: Int): List<OfficialParticipationBucketDto> =
        api.listParticipationSummary(clubId)
}
