package com.tomhempel.rbarometer.data

/**
 * Summarises local interview data that must be uploaded (or finished) before logout.
 */
object UnuploadedWorkRepository {

    data class Summary(
        val pendingQuestionnaires: Int,
        val pendingScoringReviews: Int,
        val inProgressQuestionnaires: Int,
    ) {
        val hasBlockingWork: Boolean
            get() = pendingQuestionnaires > 0 || pendingScoringReviews > 0 || inProgressQuestionnaires > 0
    }

    suspend fun summarize(): Summary {
        val codes = ClientRepository.getAllClientCodes()
        return Summary(
            pendingQuestionnaires = CompletedQuestionnaireRepository.countPendingUploads(),
            pendingScoringReviews = CoachScoringReviewRepository.countPendingUploads(),
            inProgressQuestionnaires = countInProgressQuestionnaires(codes),
        )
    }

    private suspend fun countInProgressQuestionnaires(clientCodes: List<String>): Int {
        if (clientCodes.isEmpty()) return 0
        val pairs = AnswerRepository.localAnswerPresence(clientCodes)
        var count = 0
        for ((clientCode, questionnaireId) in pairs) {
            val status = CompletedQuestionnaireRepository.getStatus(clientCode, questionnaireId)
            if (status == null || !status.isDone) count++
        }
        return count
    }
}
