<?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\Bridge\Symfony\Bundle\Service\Uploader\ImageUploader;
use CpCreation\VitiCore\Product\Model\Product;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::postPersist)]
#[AsDoctrineListener(event: Events::postUpdate)]
readonly class ProductSubscriber
{
    public function __construct(private ImageUploader $uploader)
    {
    }

    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof Product) {
            if ($entity->getSecondImage()) {
                if ($entity->getSecondImage()->getFile()) {
                    $file = $this->uploader->upload($entity->getSecondImage()->getFile());
                    $entity->setSecondImage($file);
                }
            }

            if (null === $entity->getPositionShop()) {
                $entity->setPositionShop($entity->getPosition());
            }
        }
    }

    public function postPersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof Product && null === $entity->getPositionShop()) {
            $entity->setPositionShop($entity->getPosition());
            $args->getObjectManager()->persist($entity);
            $args->getObjectManager()->flush();
        }
    }

    /**
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function postUpdate(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof Product) {
            if ($entity->getSecondImage()) {
                if ($entity->getSecondImage()->getFile()) {
                    $file = $this->uploader->upload($entity->getSecondImage()->getFile());
                    $entityManager = $args->getObjectManager();
                    $entityManager->remove($entity->getSecondImage());
                    $entity->setSecondImage($file);
                    $entityManager->persist($entity);
                    $entityManager->flush();
                }
            }
        }
    }
}
