<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Doctrine\Event;

use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\User;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Security;

class TrackCreateUpdateSubscriber implements EventSubscriber
{
    public function __construct(private readonly Security $security) {}

    public function getSubscribedEvents()
    {
        return [
            Events::prePersist,
            Events::preUpdate,
        ];
    }

    public function prePersist(LifecycleEventArgs $args): void
    {
        $object = $args->getObject();

        if ($object instanceof TrackCreationInterface) {
            $object->setCreatedAt(new \DateTimeImmutable('now'));

            if ($this->security->getUser() instanceof User) {
                $object->setCreatedBy($this->security->getUser());
            }
        }

        $this->onUpdate($object);
    }

    public function preUpdate(LifecycleEventArgs $args): void
    {
        $object = $args->getObject();

        $this->onUpdate($object);
    }

    protected function onUpdate(object $object): void
    {
        if ($object instanceof TrackUpdateInterface) {
            $object->setUpdatedAt(new \DateTimeImmutable('now'));

            if ($this->security->getUser() instanceof User) {
                $object->setUpdatedBy($this->security->getUser());
            }
        }
    }
}
