<?php

declare(strict_types=1);

namespace Dedi\SyliusTheme\Cart\Form\Extension\CartItem;

use Doctrine\ORM\EntityManagerInterface;
use Sylius\Bundle\OrderBundle\Form\Type\CartItemType;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class CartItemTypeExtension extends AbstractTypeExtension
{
    private readonly EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $originalData = $this->entityManager->getUnitOfWork()->getOriginalEntityData($form->getData());

        if (count($originalData) > 0 && array_key_exists('quantity', $originalData)) {
            $view['quantity']->vars['originalValue'] = $originalData['quantity'];

            // Reset not persisted data to keep price original value or simply the well latest persisted data (to bypass error values)
            $this->entityManager->refresh($form->getData());
            $this->entityManager->refresh($form->getData()->getOrder());
        }
    }

    public static function getExtendedTypes(): iterable
    {
        return [
            CartItemType::class,
        ];
    }
}
