class AdminPantryItem {
  final int id;
  final int userId;
  final String username;
  final String userEmail;
  final int productId;
  final String productName;
  final String? productCanonicalName;
  final int? categoryId;
  final String? categoryPath;
  final String? location;

  const AdminPantryItem({
    required this.id,
    required this.userId,
    required this.username,
    required this.userEmail,
    required this.productId,
    required this.productName,
    this.productCanonicalName,
    this.categoryId,
    this.categoryPath,
    this.location,
  });

  String get displayName {
    final canonical = productCanonicalName?.trim();
    if (canonical != null && canonical.isNotEmpty) return canonical;
    return productName;
  }

  factory AdminPantryItem.fromJson(Map<String, dynamic> json) {
    final user = (json['user'] as Map<String, dynamic>?) ?? const {};
    final product = (json['product'] as Map<String, dynamic>?) ?? const {};
    final names = <String>[];
    dynamic current = product['categoryRef'];
    while (current is Map<String, dynamic>) {
      final name = current['name']?.toString().trim();
      if (name != null && name.isNotEmpty) {
        names.insert(0, name);
      }
      current = current['parent'];
    }
    return AdminPantryItem(
      id: (json['id'] as num).toInt(),
      userId: (json['userId'] as num).toInt(),
      username: user['username'] as String? ?? '',
      userEmail: user['email'] as String? ?? '',
      productId: (json['productId'] as num).toInt(),
      productName: product['name'] as String? ?? '',
      productCanonicalName: product['canonicalName'] as String?,
      categoryId: (product['categoryId'] as num?)?.toInt(),
      categoryPath: names.isEmpty ? null : names.join(' > '),
      location: json['location'] as String?,
    );
  }
}