<?php

/*
 * This file is part of the Serenity 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\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Product\Model\ProductType;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
class ProductTypeSubscriber
{
    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();

        if ($entity instanceof ProductType) {
            $this->ensureDepotMultipleIsSet($entity);
        }
    }

    public function preUpdate(PreUpdateEventArgs $args): void
    {
        $entity = $args->getObject();

        if (!$entity instanceof ProductType) {
            return;
        }

        $before = $entity->getMultipleQuantityDepot();
        $this->ensureDepotMultipleIsSet($entity);

        // Si on a modifié la valeur pendant preUpdate, il faut recompute
        if ($entity->getMultipleQuantityDepot() !== $before) {
            /** @var EntityManagerInterface $em */
            $em = $args->getObjectManager();

            $em->getUnitOfWork()->recomputeSingleEntityChangeSet(
                $em->getClassMetadata($entity::class),
                $entity
            );
        }
    }

    private function ensureDepotMultipleIsSet(ProductType $entity): void
    {
        $depot = $entity->getMultipleQuantityDepot();

        if (null === $depot || 0 === $depot) {
            $entity->setMultipleQuantityDepot($entity->getMultipleQuantityCart());
        }
    }
}
