enum IngredientStatus { enough, missing, unitMismatch }

class IngredientPreview {
  final int ingredientId;
  final int productId;
  final String productName;
  final double requiredQuantity;
  final String requiredUnit;
  final String? note;
  final double availableQuantity;
  final IngredientStatus status;
  final double missingQuantity;

  const IngredientPreview({
    required this.ingredientId,
    required this.productId,
    required this.productName,
    required this.requiredQuantity,
    required this.requiredUnit,
    this.note,
    required this.availableQuantity,
    required this.status,
    required this.missingQuantity,
  });

  factory IngredientPreview.fromJson(Map<String, dynamic> json) {
    final rawStatus = json['status'] as String? ?? 'missing';
    final status = switch (rawStatus) {
      'enough' => IngredientStatus.enough,
      'unit_mismatch' => IngredientStatus.unitMismatch,
      _ => IngredientStatus.missing,
    };
    return IngredientPreview(
      ingredientId: json['ingredientId'] as int,
      productId: json['productId'] as int,
      productName: json['productName'] as String,
      requiredQuantity: (json['requiredQuantity'] as num).toDouble(),
      requiredUnit: json['requiredUnit'] as String? ?? '',
      note: json['note'] as String?,
      availableQuantity: (json['availableQuantity'] as num? ?? 0).toDouble(),
      status: status,
      missingQuantity: (json['missingQuantity'] as num? ?? 0).toDouble(),
    );
  }
}

class PreviewSummary {
  final int totalIngredients;
  final int enoughCount;
  final int missingCount;
  final int unitMismatchCount;
  final bool canCookExactly;

  const PreviewSummary({
    required this.totalIngredients,
    required this.enoughCount,
    required this.missingCount,
    required this.unitMismatchCount,
    required this.canCookExactly,
  });

  factory PreviewSummary.fromJson(Map<String, dynamic> json) {
    return PreviewSummary(
      totalIngredients: json['totalIngredients'] as int,
      enoughCount: json['enoughCount'] as int,
      missingCount: json['missingCount'] as int,
      unitMismatchCount: json['unitMismatchCount'] as int,
      canCookExactly: json['canCookExactly'] as bool? ?? false,
    );
  }
}

class InventoryPreview {
  final List<IngredientPreview> ingredients;
  final PreviewSummary summary;

  const InventoryPreview({
    required this.ingredients,
    required this.summary,
  });

  factory InventoryPreview.fromJson(Map<String, dynamic> json) {
    final rawIngredients = json['ingredients'] as List<dynamic>? ?? [];
    return InventoryPreview(
      ingredients: rawIngredients
          .map((e) => IngredientPreview.fromJson(e as Map<String, dynamic>))
          .toList(),
      summary: PreviewSummary.fromJson(
          json['summary'] as Map<String, dynamic>? ?? {}),
    );
  }
}
