package com.syaroful.agrilinkvocpro.control_feature.presentation.history

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syaroful.agrilinkvocpro.control_feature.core.state.ControlState
import com.syaroful.agrilinkvocpro.control_feature.data.model.ActuatorHistoryResponse
import com.syaroful.agrilinkvocpro.control_feature.data.repository.ControlRepository
import com.syaroful.agrilinkvocpro.core.utils.extention.mapToUserFriendlyError
import com.syaroful.agrilinkvocpro.data.UserPreferences
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

private const val TAG = "ControlHistoryViewModel"

class ControlHistoryViewModel(
    private val userPreferences: UserPreferences,
    private val repository: ControlRepository
) : ViewModel() {

    private val _historyState =
        MutableStateFlow<ControlState<ActuatorHistoryResponse>>(ControlState.Idle)
    val historyState: MutableStateFlow<ControlState<ActuatorHistoryResponse>> = _historyState

    init {
        getActuatorHistory()
    }

    fun getActuatorHistory() {
        _historyState.value = ControlState.Loading
        viewModelScope.launch {
            val token = userPreferences.tokenFlow.first()
            val authHeader = "Bearer $token"

            try {
                delay(500L)
                val response = repository.getActuatorHistory(authHeader = authHeader)
                if (response.isSuccessful) {
                    val data = response.body()
                    _historyState.value = ControlState.Success(data)
                    Log.d(TAG, "Successfully get Actuator History ${response.body()}")
                } else {
                    val errorBody = response.errorBody()?.string()
                    val errorMessage = errorBody ?: "Error ${response.code()}"
                    _historyState.value = ControlState.Error(errorMessage)
                }
            } catch (e: Exception) {
                val errorMessage = mapToUserFriendlyError(e)
                _historyState.value = ControlState.Error(errorMessage)

            }
        }
    }
}