import 'receipt_item.dart';

/// Satu grup transaksi dalam struk.
///
/// Setiap grup punya satu akun sumber (revenue) dan daftar itemnya sendiri.
/// Akun tujuan (asset) dipilih di level struk (dibagikan semua grup).
class ReceiptGroup {
  final String id;
  final List<ReceiptItem> items;
  final String? sourceAccountId;
  final String? sourceAccountName;

  ReceiptGroup({
    required this.id,
    List<ReceiptItem>? items,
    this.sourceAccountId,
    this.sourceAccountName,
  }) : items = items ?? [];

  double get total => items.fold(0.0, (sum, item) => sum + item.total);

  bool get hasSource => sourceAccountId != null && sourceAccountName != null;

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'items': items.map((item) => item.toJson()).toList(),
      'sourceAccountId': sourceAccountId,
      'sourceAccountName': sourceAccountName,
    };
  }

  factory ReceiptGroup.fromJson(Map<String, dynamic> json) {
    return ReceiptGroup(
      id: json['id'] as String,
      items: (json['items'] as List)
          .map((item) => ReceiptItem.fromJson(item as Map<String, dynamic>))
          .toList(),
      sourceAccountId: json['sourceAccountId'] as String?,
      sourceAccountName: json['sourceAccountName'] as String?,
    );
  }

  ReceiptGroup copyWith({
    String? id,
    List<ReceiptItem>? items,
    String? sourceAccountId,
    String? sourceAccountName,
  }) {
    return ReceiptGroup(
      id: id ?? this.id,
      items: items ?? this.items,
      sourceAccountId: sourceAccountId ?? this.sourceAccountId,
      sourceAccountName: sourceAccountName ?? this.sourceAccountName,
    );
  }
}
