package com.tomhempel.rbarometer.questionnaire

import com.tomhempel.rbarometer.data.AnswerRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object AnswerRestoreHelper {

    /**
     * Loads a prior answer from Room when the in-memory map has no value yet.
     */
    fun restoreIfMissing(
        scope: CoroutineScope,
        questionnaireId: String,
        answerMapKey: String,
        onRestored: (String) -> Unit,
    ) {
        scope.launch(Dispatchers.IO) {
            try {
                val clientCode = GlobalValues.LAST_CLIENT_CODE
                if (clientCode.isNullOrBlank() || answerMapKey.isBlank()) return@launch

                val roomId = AnswerKeyUtils.roomQuestionId(questionnaireId, answerMapKey)
                val dbAnswer = AnswerRepository.findAnswerValue(
                    AnswerRepository.getAnswersForClient(clientCode),
                    roomId,
                )
                if (!dbAnswer.isNullOrBlank()) {
                    withContext(Dispatchers.Main) { onRestored(dbAnswer) }
                }
            } catch (_: Exception) {
            }
        }
    }
}
