/// Repository Implementation: Reviews
///
/// Implements the reviews repository interface.
library;

import 'package:worker/features/reviews/data/datasources/reviews_remote_datasource.dart';
import 'package:worker/features/reviews/domain/entities/review.dart';
import 'package:worker/features/reviews/domain/entities/review_statistics.dart';
import 'package:worker/features/reviews/domain/repositories/reviews_repository.dart';

/// Reviews repository implementation
class ReviewsRepositoryImpl implements ReviewsRepository {
  const ReviewsRepositoryImpl(this._remoteDataSource);

  final ReviewsRemoteDataSource _remoteDataSource;

  @override
  Future<List<Review>> getProductReviews({
    required String itemId,
    int limitPageLength = 10,
    int limitStart = 0,
  }) async {
    final models = await _remoteDataSource.getProductReviews(
      itemId: itemId,
      limitPageLength: limitPageLength,
      limitStart: limitStart,
    );

    // Convert models to entities and sort by date (newest first)
    final reviews = models.map((model) => model.toEntity()).toList();

    reviews.sort((a, b) {
      if (a.reviewDate == null && b.reviewDate == null) return 0;
      if (a.reviewDate == null) return 1;
      if (b.reviewDate == null) return -1;
      return b.reviewDate!.compareTo(a.reviewDate!);
    });

    return reviews;
  }

  @override
  Future<ReviewStatistics> getProductReviewStatistics({
    required String itemId,
  }) async {
    final response = await _remoteDataSource.getProductReviewsWithStats(
      itemId: itemId,
      limitPageLength: 50, // Get enough reviews to calculate stats
      limitStart: 0,
    );

    // Return statistics from API (already calculated server-side)
    return response.statistics.toEntity();
  }

  @override
  Future<void> submitReview({
    required String itemId,
    required double rating,
    required String comment,
    String? name,
  }) async {
    await _remoteDataSource.submitReview(
      itemId: itemId,
      rating: rating,
      comment: comment,
      name: name,
    );
  }

  @override
  Future<void> deleteReview({required String name}) async {
    await _remoteDataSource.deleteReview(name: name);
  }
}
