package de.krisenvorrat.app.domain.usecase

import de.krisenvorrat.app.data.db.entity.ItemEntity
import javax.inject.Inject

internal class CalculateSupplyRangeUseCase @Inject constructor() {

    companion object {
        const val DEFAULT_HOUSEHOLD_SIZE = 2
        const val DEFAULT_DAILY_KCAL_PER_PERSON = 2000
        const val DEFAULT_TOTAL_DAILY_KCAL = DEFAULT_HOUSEHOLD_SIZE * DEFAULT_DAILY_KCAL_PER_PERSON
    }

    operator fun invoke(
        items: List<ItemEntity>,
        totalDailyKcal: Int = DEFAULT_TOTAL_DAILY_KCAL
    ): Double {
        val dailyNeed = totalDailyKcal
        if (dailyNeed <= 0) return 0.0

        val totalKcal = items.sumOf { item ->
            val kcalPerKg = item.kcalPerKg ?: return@sumOf 0.0
            val grams = convertToGrams(item.quantity, item.unit) ?: return@sumOf 0.0
            (grams / 1000.0) * kcalPerKg
        }

        return totalKcal / dailyNeed
    }

    private fun convertToGrams(quantity: Double, unit: String): Double? {
        return when (unit.lowercase().trim()) {
            "g" -> quantity
            "kg" -> quantity * 1000.0
            "mg" -> quantity / 1000.0
            else -> null
        }
    }
}
