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

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

    /**
     * @throws \Exception
     */
    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof File) {
            if ($entity->getFile()) {
                $file = $this->uploader->upload($entity->getFile());
                $entity->setPath($file->getPath());
                $entity->setSize($file->getSize());
                $entity->setMimeType($file->getMimeType());
                $entity->setOriginalName($file->getOriginalName());
            }
        }
    }

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