<?php

namespace KupShop\ComponentsBundle\Twig\Components\Product\Reviews;

use KupShop\CatalogBundle\Util\ReviewsUtil;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Interfaces\Microdata;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use KupShop\ComponentsBundle\Twig\DataProvider\MicrodataProvider;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Product/Reviews/Header/Header.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class Header extends BaseComponent implements Microdata
{
    use DefaultActionTrait;
    use ProductDataTrait;

    public function __construct(private readonly ReviewsUtil $reviewsUtil)
    {
    }

    public ?string $title = null;
    public ?string $button_title = null;

    public ?bool $show_stars_bottom = false;

    public function getRating(): ?array
    {
        return $this->product->fetchRating();
    }

    public function getUserAlreadyRated(): bool
    {
        return $this->reviewsUtil->hasUserAlreadyRated($this->id_product);
    }

    public function initMicrodata(): array
    {
        if (($rating = $this->getRating()) && !empty($rating['rating_count'])) {
            return [
                MicrodataProvider::PRODUCT => [
                    'aggregateRating' => [
                        '@type' => 'AggregateRating',
                        'ratingValue' => round($rating['rating'], 1),
                        'reviewCount' => $rating['rating_count'],
                    ],
                ],
            ];
        }

        return [];
    }
}
