class ReceiptAlias {
  final int id;
  final String receiptName;
  final int productId;
  final int? ownerId;
  final bool isGlobal;
  final String? productName;
  final String? productCanonicalName;

  const ReceiptAlias({
    required this.id,
    required this.receiptName,
    required this.productId,
    required this.ownerId,
    required this.isGlobal,
    this.productName,
    this.productCanonicalName,
  });

  bool get isPrivate => !isGlobal;

  String get displayProductName {
    final canonical = productCanonicalName?.trim();
    if (canonical != null && canonical.isNotEmpty) return canonical;
    final fallback = productName?.trim();
    if (fallback != null && fallback.isNotEmpty) return fallback;
    return '#$productId';
  }

  factory ReceiptAlias.fromJson(Map<String, dynamic> json) {
    final product = json['product'];
    final productMap = product is Map<String, dynamic>
        ? product
        : const <String, dynamic>{};

    return ReceiptAlias(
      id: (json['id'] as num).toInt(),
      receiptName: (json['receiptName'] ?? '').toString(),
      productId: (json['productId'] as num?)?.toInt() ??
          (productMap['id'] as num?)?.toInt() ??
          0,
      ownerId: (json['ownerId'] as num?)?.toInt(),
      isGlobal: json['isGlobal'] == true,
      productName: productMap['name']?.toString(),
      productCanonicalName: productMap['canonicalName']?.toString(),
    );
  }
}
