<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Marketing;

use CpCreation\VitiCore\Product\Model\Product;

final readonly class ProductReviewCardSummaryProvider
{
    public const MINIMUM_REVIEW_COUNT = 3;

    public function __construct(
        private ProductReviewConfigurationProvider $configurationProvider,
        private PublishedProductReviewRatingCollectionProvider $ratingProvider,
    ) {}

    /** @param iterable<Product> $products */
    public function getForProducts(
        iterable $products,
        ?\DateTimeImmutable $now = null,
    ): ProductReviewCardData {
        if (!$this->configurationProvider->isEnabled()) {
            return new ProductReviewCardData(false, []);
        }

        $summaries = [];
        foreach ($this->ratingProvider->getPublishedRatingSummaries($products, $now) as $productId => $summary) {
            $summaries[$productId] = new ProductReviewCardSummary(
                reviewCount: $summary->reviewCount,
                ratingValue: $summary->reviewCount >= self::MINIMUM_REVIEW_COUNT
                    ? $summary->ratingValue
                    : null,
            );
        }

        return new ProductReviewCardData(true, $summaries);
    }
}
