package com.dano.test1.questionnaire

import android.content.Context
import com.dano.test1.LanguageManager
import com.dano.test1.MyApp
import com.dano.test1.data.Answer
import com.dano.test1.data.AnswerRepository
import com.dano.test1.data.ClientAnswersCache
import com.dano.test1.data.ClientRepository
import com.dano.test1.data.CompletedQuestionnaireRepository
import com.dano.test1.data.CompletedQuestionnaire
import com.dano.test1.data.Question
import com.dano.test1.data.Questionnaire
import com.dano.test1.network.SyncLog
import com.dano.test1.notification.UploadReminderScheduler

object QuestionnairePersistence {

    suspend fun saveAnswers(
        context: Context,
        answers: Map<String, Any>,
        questionnaireId: String,
        languageId: String,
        questions: List<QuestionItem> = emptyList(),
    ) {
        val persistedAnswers = canonicalPersistedAnswers(answers, questions)
        SyncLog.d("QUESTIONNAIRE", "Persisting ${persistedAnswers.size} answer field(s)")
        if (!ClientAssignmentGuard.canPersistAnswers(context, answers)) {
            val clientCode = answers["client_code"] as? String
            SyncLog.w("QUESTIONNAIRE", "Skipping save for unassigned ${SyncLog.clientRef(clientCode)}")
            return
        }

        val clientCode = answers["client_code"] as? String ?: return
        val db = MyApp.database

        ClientRepository.ensureClient(clientCode)
        db.questionnaireDao().insertQuestionnaire(Questionnaire(id = questionnaireId))

        AnswerRepository.deleteAnswersForClientAndQuestionnaire(clientCode, questionnaireId)

        val questionEntities = persistedAnswers.keys
            .filterNot { it.startsWith("client") }
            .map { key ->
                Question(
                    questionId = AnswerKeyUtils.roomQuestionId(questionnaireId, key),
                    questionnaireId = questionnaireId,
                    question = LanguageManager.getText(languageId, key),
                )
            }
        db.questionDao().insertQuestions(questionEntities)

        val answerEntities = persistedAnswers.entries
            .filterNot { it.key.startsWith("client") }
            .map { (key, value) ->
                Answer(
                    clientCode = clientCode,
                    questionId = AnswerKeyUtils.roomQuestionId(questionnaireId, key),
                    answerValue = value.toString(),
                )
            }
        AnswerRepository.insertAnswers(answerEntities)
        ClientAnswersCache.invalidate(clientCode)

        CompletedQuestionnaireRepository.insert(
            CompletedQuestionnaire(
                clientCode = clientCode,
                questionnaireId = questionnaireId,
                isDone = true,
                sumPoints = null,
            ),
        )
        UploadReminderScheduler.schedule(context)
    }

    private fun canonicalPersistedAnswers(
        answers: Map<String, Any>,
        questions: List<QuestionItem>,
    ): Map<String, Any> {
        if (questions.isEmpty()) return answers

        val filtered = answers.toMutableMap()
        for (question in questions) {
            val canonicalKey = answerKeyFor(question) ?: continue
            val shortId = question.id.takeIf { it.isNotBlank() && it != canonicalKey } ?: continue
            filtered.remove(shortId)
        }
        return filtered
    }

    private fun answerKeyFor(question: QuestionItem): String? = when (question) {
        is QuestionItem.RadioQuestion -> question.question ?: question.id
        is QuestionItem.MultiCheckboxQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.StringSpinnerQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.ValueSpinnerQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.FreeTextQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.DateSpinnerQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.SliderQuestion -> question.question.ifBlank { question.id }
        is QuestionItem.ClientCoachCodeQuestion -> null
        is QuestionItem.GlassScaleQuestion -> null
        is QuestionItem.LastPage -> null
    }
}
