<?php

namespace KupShop\GTMBundle\ServerSideGTMEvent;

use KupShop\GTMBundle\Utils\DataLoaders\PurchaseState;
use KupShop\OrderingBundle\Event\CartItemEvent;
use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Contracts\Service\Attribute\Required;

class CartAddItemEvent extends AbstractServerSideGTMEvent
{
    #[Required]
    public PurchaseState $purchaseState;

    public function getPayload(Event $event): array
    {
        if (!($event instanceof CartItemEvent)) {
            return [];
        }

        $product = $event->getProduct();
        $product->fetchVariations();
        if (empty($product->producer)) {
            $product->fetchProducer();
        }
        $product->fetchImages('product_gallery');

        $item = $this->productLoader->loadProductObject($product);
        $item['quantity'] = abs($event->getDifferences()['pieces_diff'] ?? 1);
        $item['index'] = 1;
        if (($soldOut = $this->purchaseState->getSoldOut($product)) !== null) {
            $item['soldOut'] = $soldOut;
        }

        $params = $this->getCommonData($event);
        $params['items'] = [$item];

        return [
            'events' => [
                [
                    'name' => $this->getEventName(),
                    'user_id' => $this->getUserId(),
                    'client_id' => $this->getClientId(),
                    'ga3_session_id' => $this->getGA3SessionId(),
                    'params' => $params,
                ],
            ],
        ];
    }

    protected function getCommonData(Event $event): array
    {
        $dbcfg = \Settings::getDefault();
        $product = $event->getProduct();

        $request = $this->getRequest();

        return array_merge(parent::getCommonData($event), [
            'page_title' => $product->meta_title ?: $product->title.' - '.$dbcfg['shop_title'],
            'value' => $this->getEventPrice($event)->asFloat(),
            'event_id' => $request->cookies->get('gtm_event_uid'),
        ]);
    }

    private function getEventPrice(Event $event): \Decimal
    {
        /** @var CartItemEvent $event */
        $price = $event->getProduct()->getProductPrice()->getPriceWithVat();
        $pieces = (int) abs($event->getDifferences()['pieces_diff'] ?? 1);

        return $price->mul(toDecimal($pieces));
    }

    protected function getEventName(): string
    {
        return 'add_to_cart';
    }
}
