package de.krisenvorrat.app.domain.model

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
enum class AgeGroup(val label: String, val defaultKcal: Int) {
    KLEINKIND("Kleinkind (1–3 J.)", 1000),
    KIND_4_6("Kind (4–6 J.)", 1400),
    KIND_7_9("Kind (7–9 J.)", 1700),
    KIND_10_12("Kind (10–12 J.)", 2000),
    JUGENDLICH("Jugendlich (13–17 J.)", 2400),
    ERWACHSENER("Erwachsener", 2000)
}

@Serializable
data class AgeGroupEntry(
    val ageGroup: AgeGroup,
    val count: Int,
    val kcalPerDay: Int
)

internal fun List<AgeGroupEntry>.totalDailyKcal(): Int = sumOf { it.count * it.kcalPerDay }

internal fun defaultAgeGroups(): List<AgeGroupEntry> = AgeGroup.entries.map { group ->
    AgeGroupEntry(
        ageGroup = group,
        count = if (group == AgeGroup.ERWACHSENER) 2 else 0,
        kcalPerDay = group.defaultKcal
    )
}

private val ageGroupsJson = Json { ignoreUnknownKeys = true }

internal fun List<AgeGroupEntry>.toJson(): String = ageGroupsJson.encodeToString(
    kotlinx.serialization.builtins.ListSerializer(AgeGroupEntry.serializer()),
    this
)

internal fun parseAgeGroupsFromJson(json: String?): List<AgeGroupEntry> {
    if (json.isNullOrBlank()) return defaultAgeGroups()
    return try {
        ageGroupsJson.decodeFromString(
            kotlinx.serialization.builtins.ListSerializer(AgeGroupEntry.serializer()),
            json
        )
    } catch (e: Exception) {
        defaultAgeGroups()
    }
}
