package app.closer.ui.questions

import app.closer.domain.model.ChoiceAnswerConfigImpl
import app.closer.domain.model.LocalAnswer
import app.closer.domain.model.Question
import app.closer.domain.model.ThisOrThatAnswerConfigImpl

fun LocalQuestionUiState.withLocalAnswer(answer: LocalAnswer?): LocalQuestionUiState {
    answer ?: return copy(submitted = false, isRevealed = false)
    return copy(
        submitted = true,
        isRevealed = answer.isRevealed,
        pendingWrittenText = answer.writtenText.orEmpty(),
        pendingSelectedOptionIds = answer.selectedOptionIds,
        pendingScaleValue = answer.scaleValue ?: pendingScaleValue
    )
}

fun LocalQuestionUiState.toLocalAnswer(question: Question): LocalAnswer {
    return LocalAnswer(
        questionId = question.id,
        questionText = question.text,
        category = question.category,
        answerType = question.type,
        writtenText = pendingWrittenText.takeIf { question.type == "written" && it.isNotBlank() },
        selectedOptionIds = when (question.type) {
            "single_choice", "multi_choice", "this_or_that" -> pendingSelectedOptionIds
            else -> emptyList()
        },
        selectedOptionTexts = selectedOptionTexts(question, pendingSelectedOptionIds),
        scaleValue = pendingScaleValue.takeIf { question.type == "scale" }
    )
}

internal fun selectedOptionTexts(
    question: Question,
    selectedOptionIds: List<String>
): List<String> {
    if (selectedOptionIds.isEmpty()) return emptyList()
    return when (question.type) {
        "this_or_that" -> {
            val cfg = question.answerConfig as? ThisOrThatAnswerConfigImpl
            listOfNotNull(cfg?.config?.optionA, cfg?.config?.optionB)
                .filter { it.id in selectedOptionIds }
                .map { it.text }
        }
        "single_choice", "multi_choice" -> {
            val cfg = question.answerConfig as? ChoiceAnswerConfigImpl
            cfg?.config?.options
                ?.filter { it.id in selectedOptionIds }
                ?.map { it.text }
                ?: emptyList()
        }
        else -> emptyList()
    }
}
