<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\GTM\Events;

use KupShop\CatalogBundle\ProductList\ProductCollection;
use KupShop\ComponentsBundle\Interfaces\GTMComponentInterface;
use KupShop\ComponentsBundle\Twig\DataProvider\ProductDataProvider;
use KupShop\ContentBundle\Entity\ProductUnified;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem;
use Symfony\Contracts\Service\Attribute\Required;

class ProductClick implements GTMComponentInterface
{
    #[Required]
    public ProductDataProvider $productDataProvider;

    #[Required]
    public \KupShop\ComponentsBundle\GTM\Utils\DataLoaders\Products $productLoader;

    /**
     * @param \KupShop\ComponentsBundle\Twig\Components\ProductList\Item|object $component
     */
    public function getPushData($component): object
    {
        return $this->createDataContainer($component->getProductUnified(), $component->getUrl());
    }

    public function getPushDataFromCartItem(ProductPurchaseItem $item): object
    {
        $product = $item->getProduct();

        if ($item->getIdVariation()) {
            // Use ProductCollection to fetch variations bcs we need variation entities
            $pc = new ProductCollection([$product->id => $product]);
            $pc->fetchVariationsEntities();
            $productUnified = new ProductUnified($product, $product->fetchVariations());
            $productUnified->selectVariation($item->getIdVariation());
        } else {
            $productUnified = new ProductUnified($product);
        }

        $url = path('products', ['id' => $product->id, 'name' => StringUtil::slugify($product->title)]);

        return $this->createDataContainer($productUnified, $url);
    }

    private function createDataContainer(ProductUnified $product, string $url): object
    {
        $products = $this->productLoader->getProducts([$product]);

        $dataContainer = new \stdClass();
        $dataContainer->event = 'select_item';
        $dataContainer->action = 'click';
        $dataContainer->target = $url;
        $dataContainer->ecommerce = (object) [
            'items' => $products,
            'item_list_name' => '@item_list_name',
            'item_list_id' => '@item_list_id',
        ];

        return $dataContainer;
    }
}
