<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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\Cart\Model\CartItem;
use CpCreation\VitiCore\Product\ProductVariantSkuResolver;
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)]
final readonly class CartItemSkuSnapshotSubscriber
{
    public function __construct(
        private ProductVariantSkuResolver $skuResolver,
    ) {}

    public function prePersist(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        if (!$entity instanceof CartItem || null !== $entity->getSkuSnapshot()) {
            return;
        }

        $this->capture($entity);
    }

    public function preUpdate(PreUpdateEventArgs $event): void
    {
        $entity = $event->getObject();
        if (!$entity instanceof CartItem) {
            return;
        }

        $variantChanged = $event->hasChangedField('variant');
        if (null !== $entity->getSkuSnapshot() && (!$variantChanged || $entity->getCart()?->isCheckoutOrdered())) {
            return;
        }

        $before = $entity->getSkuSnapshot();
        $this->capture($entity);
        if ($before === $entity->getSkuSnapshot()) {
            return;
        }

        $entityManager = $event->getObjectManager();
        if ($entityManager instanceof EntityManagerInterface) {
            $entityManager->getUnitOfWork()->recomputeSingleEntityChangeSet(
                $entityManager->getClassMetadata(CartItem::class),
                $entity,
            );
        }
    }

    private function capture(CartItem $item): void
    {
        $variant = $item->getVariant();
        $item->setSkuSnapshot(null !== $variant ? $this->skuResolver->resolve($variant) : null);
    }
}
