package com.prodhack.moscow2025.presentation.screens.resumeDetails

import com.prodhack.moscow2025.domain.models.ResumeModel
import com.prodhack.moscow2025.domain.usecase.resumes.GetResumeInfoUseCase
import com.prodhack.moscow2025.domain.usecase.resumes.RefreshResumeUseCase
import com.prodhack.moscow2025.presentation.utils.UIState
import com.prodhack.moscow2025.presentation.utils.base.BaseViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.StateFlow
import org.koin.android.annotation.KoinViewModel
import org.koin.core.annotation.Provided

@KoinViewModel
class ResumeDetailsViewModel(
	@Provided resumeId: String,
	private val getResumeInfoUseCase: GetResumeInfoUseCase,
	private val refreshResumeUseCase: RefreshResumeUseCase
) : BaseViewModel() {
	private val _resumeState = MutableUIStateFlow<ResumeModel>()
	val resumeState: StateFlow<UIState<ResumeModel>> = _resumeState
	private val id = resumeId
	private var pollingStarted = false

	private fun startPredictionPolling() {
		if (pollingStarted) return
		pollingStarted = true
		viewModelScope.launch {
			while (true) {
				val current = (_resumeState.value as? UIState.Success)?.data
				if (current?.prediction?.first != null || current?.prediction?.second != null) break
				delay(2000)
				val refreshed = refreshResumeUseCase(id)
				if (refreshed.isSuccess) {
					_resumeState.value = UIState.Success(refreshed.getOrNull()!!)
				}
			}
		}
	}

	fun loadResume(resumeId: String) {
		getResumeInfoUseCase(resumeId).collectRequest(_resumeState)
		viewModelScope.launch {
			resumeState.collect {
				val data = (it as? UIState.Success)?.data
				if (data?.prediction == null) {
					startPredictionPolling()
				}
			}
		}
	}

	init {
		loadResume(resumeId)
	}
}
