<?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\Manager\CarrierProviderManager;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\Uploader\FileUploader;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
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)]
class ShippingConfigSubscriber
{
    public function __construct(private CarrierProviderManager $manager, private FileUploader $uploader)
    {
    }

    /**
     * @throws \Exception
     */
    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFileSup()) {
                $file = $this->uploader->upload($entity->getFileSup()->getFile());
                $entity->setFileSup($file);
            }
        }
    }

    /**
     * @throws \Exception
     */
    public function postPersist(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFile() || $entity->getFileSup()) {
                $this->manager->createProviderManager($entity);
            }
        }
    }

    /**
     * @throws \Exception
     */
    public function postUpdate(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFileSup()) {
                if ($entity->getFileSup()->getFile()) {
                    $entityManager = $event->getObjectManager();
                    $entityManager->remove($entity->getFileSup());
                    $file = $this->uploader->upload($entity->getFileSup()->getFile());
                    $entity->setFileSup($file);
                    $entityManager->persist($entity);
                    $entityManager->flush();
                }
            }
            if ($entity->getFile() || $entity->getFileSup()) {
                $this->manager->createProviderManager($entity);
            }
        }
    }
}
