package dev.adriankuta.flights.ui.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.adriankuta.flights.core.util.Result
import dev.adriankuta.flights.core.util.asResult
import dev.adriankuta.flights.domain.search.ObserveAirportsUseCase
import dev.adriankuta.flights.domain.types.AirportInfo
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class HomeScreenViewModel @Inject constructor(
    private val observeAirportsUseCase: ObserveAirportsUseCase,
) : ViewModel() {

    internal val uiState = homeUiState(
        useCase = observeAirportsUseCase,
    )
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomeUiState.Loading,
        )
}

private fun homeUiState(
    useCase: ObserveAirportsUseCase,
): Flow<HomeUiState> {
    return useCase()
        .asResult()
        .map { result ->
            when (result) {
                is Result.Error -> HomeUiState.Error(result.exception)
                Result.Loading -> HomeUiState.Loading
                is Result.Success -> HomeUiState.Success(result.data.orEmpty())
            }
        }
}

internal sealed interface HomeUiState {
    data object Loading : HomeUiState
    data class Success(val airports: List<AirportInfo>) : HomeUiState
    data class Error(val exception: Throwable) : HomeUiState
}
