class Review {
  final int id;
  final int productId;
  final String reviewer;
  final String reviewerEmail;
  final String review;
  final int rating;
  final bool verified;
  final DateTime dateCreated;
  final String? reviewerAvatarUrl;

  Review({
    required this.id,
    required this.productId,
    required this.reviewer,
    required this.reviewerEmail,
    required this.review,
    required this.rating,
    this.verified = false,
    required this.dateCreated,
    this.reviewerAvatarUrl,
  });

  factory Review.fromJson(Map<String, dynamic> json) {
    return Review(
      id: json['id'] ?? 0,
      productId: json['product_id'] ?? 0,
      reviewer: json['reviewer'] ?? '',
      reviewerEmail: json['reviewer_email'] ?? '',
      review: json['review'] ?? '',
      rating: json['rating'] ?? 0,
      verified: json['verified'] ?? false,
      dateCreated: json['date_created'] != null
          ? DateTime.parse(json['date_created'])
          : DateTime.now(),
      reviewerAvatarUrl: json['reviewer_avatar_urls']?['96'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'product_id': productId,
      'reviewer': reviewer,
      'reviewer_email': reviewerEmail,
      'review': review,
      'rating': rating,
      'verified': verified,
      'date_created': dateCreated.toIso8601String(),
    };
  }
}

class ProductRating {
  final double averageRating;
  final int ratingCount;
  final Map<int, int> ratingBreakdown; // rating -> count

  ProductRating({
    required this.averageRating,
    required this.ratingCount,
    required this.ratingBreakdown,
  });

  factory ProductRating.fromJson(Map<String, dynamic> json) {
    final breakdown = <int, int>{};
    if (json['rating_breakdown'] != null) {
      (json['rating_breakdown'] as Map).forEach((key, value) {
        breakdown[int.parse(key.toString())] = value as int;
      });
    }

    return ProductRating(
      averageRating: (json['average_rating'] ?? 0.0).toDouble(),
      ratingCount: json['rating_count'] ?? 0,
      ratingBreakdown: breakdown,
    );
  }
}

