<?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\User\Model\User;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
class UserSubscriber
{
    public function __construct(private UserPasswordHasherInterface $passwordEncoder)
    {
    }

    public function prePersist(LifecycleEventArgs $event): void
    {
        $entity = $event->getObject();
        if ($entity instanceof User) {
            $this->hashPassword($entity);
        }
    }

    public function preUpdate(PreUpdateEventArgs $event): void
    {
        $entity = $event->getObject();
        if (!$entity instanceof User) {
            return;
        }

        if (!$this->hashPassword($entity)) {
            return;
        }

        $entityManager = $event->getObjectManager();
        $metadata = $entityManager->getClassMetadata($entity::class);
        $entityManager->getUnitOfWork()->recomputeSingleEntityChangeSet($metadata, $entity);
    }

    private function hashPassword(User $user): bool
    {
        $plainPassword = $user->getPlainPassword();
        if (null === $plainPassword || '' === trim($plainPassword)) {
            return false;
        }

        $user->setPassword($this->passwordEncoder->hashPassword($user, $plainPassword));
        $user->setPlainPassword(null);

        return true;
    }
}
