package com.isidroid.c23.domain.use_case

import android.content.Context
import com.isidroid.job_sender.SendJobWorker
import com.isidroid.c23.ext.isDebug
import com.isidroid.c23.ui.screen.home.HomeContract
import com.isidroid.core.FlowResult
import com.isidroid.session.repository.SessionRepository
import com.isidroid.spot.repository.ActiveSpotRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class HomeUseCase @Inject constructor(
    @ApplicationContext private val context: Context,
    private val sessionRepository: SessionRepository,
    private val activeSpotRepository: ActiveSpotRepository
) {
    fun createSession() = flow {
        emit(FlowResult.Loading)

        SendJobWorker.create(context)

        val maxDelay = if (isDebug()) 0 else 3_000
        val startedAt = System.currentTimeMillis()

        val hasSession = sessionRepository.hasCurrent
        val hasDefaultSpot = activeSpotRepository.getDefaultSpot() != null

        val ts = System.currentTimeMillis() - startedAt

        val navigation = when {
            !hasSession -> HomeContract.Effect.Navigation.ToLogin
            !hasDefaultSpot -> HomeContract.Effect.Navigation.ToSelectSpot(
//                lat = 37.2451678,
//                lng = -121.9752617

                lat = 37.2451678,
                lng = -121.9752617,
            )

            else -> HomeContract.Effect.Navigation.ToSelectContent
        }

        val delay = maxDelay - ts
        delay(delay)

        emit(FlowResult.Success(navigation))
    }
}
