package com.tomhempel.rbarometer.data

/**
 * In-memory cache of answers for the active client to avoid repeated Room reads
 * when evaluating questionnaire conditions (≤10 questionnaires per client).
 */
object ClientAnswersCache {

    private var cachedClient: String? = null
    private val byQuestionnaire = mutableMapOf<String, List<Answer>>()
    private var allAnswers: List<Answer>? = null

    suspend fun answersForQuestionnaire(clientCode: String, questionnaireId: String): List<Answer> {
        ensureClient(clientCode)
        return byQuestionnaire.getOrPut(questionnaireId) {
            AnswerRepository.getAnswersForClientAndQuestionnaire(clientCode, questionnaireId)
        }
    }

    suspend fun allForClient(clientCode: String): List<Answer> {
        ensureClient(clientCode)
        return allAnswers ?: AnswerRepository.getAnswersForClient(clientCode).also { allAnswers = it }
    }

    fun invalidate(clientCode: String? = null) {
        if (clientCode == null || cachedClient == null || cachedClient.equals(clientCode, ignoreCase = true)) {
            cachedClient = null
            byQuestionnaire.clear()
            allAnswers = null
        }
    }

    private fun ensureClient(clientCode: String) {
        if (!cachedClient.equals(clientCode, ignoreCase = true)) {
            cachedClient = clientCode
            byQuestionnaire.clear()
            allAnswers = null
        }
    }
}
