package de.krisenvorrat.app.domain.usecase

import de.krisenvorrat.app.data.db.entity.ItemEntity
import de.krisenvorrat.app.domain.model.ExpiryUrgency
import de.krisenvorrat.app.domain.model.ExpiryWarning
import java.time.LocalDate
import java.time.temporal.ChronoUnit
import javax.inject.Inject

internal class GetExpiryWarningsUseCase @Inject constructor() {

    companion object {
        const val URGENT_MONTHS = 6L
        const val WARNING_MONTHS = 12L
    }

    operator fun invoke(
        items: List<ItemEntity>,
        referenceDate: LocalDate = LocalDate.now()
    ): List<ExpiryWarning> {
        val urgentCutoff = referenceDate.plusMonths(URGENT_MONTHS)
        val warningCutoff = referenceDate.plusMonths(WARNING_MONTHS)

        return items
            .mapNotNull { item ->
                val expiryDate = item.expiryDate ?: return@mapNotNull null
                if (expiryDate.isAfter(warningCutoff)) return@mapNotNull null

                val daysUntil = ChronoUnit.DAYS.between(referenceDate, expiryDate)
                val urgency = if (!expiryDate.isAfter(urgentCutoff)) {
                    ExpiryUrgency.URGENT
                } else {
                    ExpiryUrgency.WARNING
                }
                ExpiryWarning(
                    item = item,
                    daysUntilExpiry = daysUntil,
                    urgency = urgency
                )
            }
            .sortedBy { it.daysUntilExpiry }
    }
}
