import 'package:hl_lieferservice/feature/scan/model/article.dart';

import '../../model/delivery.dart';

Map<String, ArticleGroup> initializeArticleGroups(List<Delivery> deliveries) {
  Map<String, ArticleGroup> articleGroups = {};

  // Alle Artikel aus allen Lieferungen durchgehen
  for (var delivery in deliveries) {
    for (var article in delivery.articles) {
      if (articleGroups.containsKey(article.articleNumber)) {
        // Artikel bereits vorhanden, Anzahl erhöhen
        if (article.scannable) {
          articleGroups[article.articleNumber]!.scannedCount += article.scannedAmount;
          articleGroups[article.articleNumber]!.totalCount += article.amount;
          articleGroups[article.articleNumber]!.deliveryIds.add(delivery);
        }
      } else {
        if (article.scannable) {
          // Neuer Artikel, hinzufügen
          articleGroups[article.articleNumber] = ArticleGroup(
            deliveryIds: {delivery},
            articleName: article.name,
            articleNumber: article.articleNumber,
            scannedCount: article.scannedAmount,
            internalRowId: article.internalId.toString(),
            totalCount: article.amount,
          );
        }
      }
    }
  }

  return articleGroups;
}