package de.tsschulz.tt_tagebuch.shared.state

import de.tsschulz.tt_tagebuch.shared.api.ClubApprovalsApi
import de.tsschulz.tt_tagebuch.shared.api.models.ClubAccessDecisionBody
import de.tsschulz.tt_tagebuch.shared.api.models.PendingUserClubJoinDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

data class PendingApprovalsState(
    val pending: List<PendingUserClubJoinDto> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null,
)

class PendingApprovalsManager(
    private val clubApprovalsApi: ClubApprovalsApi,
) {
    private val _state = MutableStateFlow(PendingApprovalsState())
    val state: StateFlow<PendingApprovalsState> = _state.asStateFlow()

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

    suspend fun load(clubId: Int) {
        _state.update { it.copy(isLoading = true, error = null) }
        try {
            val list = clubApprovalsApi.listPending(clubId)
            _state.update { it.copy(pending = list, isLoading = false, error = null) }
        } catch (t: Throwable) {
            _state.update {
                it.copy(isLoading = false, error = t.toUserMessage("Freigaben konnten nicht geladen werden"))
            }
        }
    }

    suspend fun approve(clubId: Int, userId: Int) {
        clubApprovalsApi.approve(ClubAccessDecisionBody(clubid = clubId, userid = userId))
        load(clubId)
    }

    suspend fun reject(clubId: Int, userId: Int) {
        clubApprovalsApi.reject(ClubAccessDecisionBody(clubid = clubId, userid = userId))
        load(clubId)
    }
}
