<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig;

use CpCreation\VitiCore\Marketing\ProductReviewConfigurationProvider;
use CpCreation\VitiCore\Marketing\PublishedProductReviewRatingProvider;
use CpCreation\VitiCore\Product\Model\Product;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class ProductReviewSeoExtension extends AbstractExtension
{
    public function __construct(
        private readonly PublishedProductReviewRatingProvider $ratingProvider,
        private readonly ProductReviewConfigurationProvider $configurationProvider,
    ) {}

    public function getFunctions(): array
    {
        return [
            new TwigFunction('product_review_aggregate_rating', $this->getAggregateRating(...)),
        ];
    }

    /**
     * @return array{
     *     '@type': 'AggregateRating',
     *     ratingValue: float,
     *     reviewCount: int,
     *     bestRating: int,
     *     worstRating: int
     * }|null
     */
    public function getAggregateRating(Product $product): ?array
    {
        if (!$this->configurationProvider->isEnabled()) {
            return null;
        }

        $summary = $this->ratingProvider->getPublishedRatingSummary($product);
        if (null === $summary) {
            return null;
        }

        return [
            '@type' => 'AggregateRating',
            'ratingValue' => round($summary->ratingValue, 2),
            'reviewCount' => $summary->reviewCount,
            'bestRating' => 5,
            'worstRating' => 1,
        ];
    }
}
