package de.krisenvorrat.app.domain.usecase

import de.krisenvorrat.app.data.db.entity.CategoryEntity
import de.krisenvorrat.app.data.db.entity.ItemEntity
import de.krisenvorrat.app.domain.model.CategorySummary
import javax.inject.Inject

internal class CalculateCategorySummaryUseCase @Inject constructor() {

    operator fun invoke(
        items: List<ItemEntity>,
        categories: List<CategoryEntity>
    ): List<CategorySummary> {
        val categoryMap = categories.associate { it.id to it.name }
        return items
            .groupBy { it.categoryId }
            .map { (categoryId, categoryItems) ->
                CategorySummary(
                    categoryId = categoryId,
                    categoryName = categoryMap[categoryId] ?: "Unbekannt",
                    itemCount = categoryItems.size,
                    totalValue = categoryItems.sumOf { it.quantity * it.unitPrice }
                )
            }
            .sortedBy { it.categoryName }
    }
}
