<?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\IsSoftDeletable;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Gedmo\Sortable\Sortable;

#[AsDoctrineListener(event: Events::preRemove)]
class SoftDeletableSubscriber
{
    public function preRemove(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        if ($entity instanceof IsSoftDeletable) {
            if ($entity instanceof Sortable) {
                $entity->setPosition(-1);
            }
            $entity->markDeleted();
            $om = $event->getObjectManager();
            $om->persist($entity);
            $om->flush();
        }
    }
}
