<?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 Serenity\CoreBundle\Slug\Doctrine\EventListener;

use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Serenity\CoreBundle\Shared\Feature\SluggableInterface;
use Serenity\CoreBundle\Slug\Entity\SlugHistory;
use Symfony\Component\Uid\Uuid;

#[AsDoctrineListener(event: Events::onFlush)]
final class SlugHistoryOnFlush
{
    public function __invoke(OnFlushEventArgs $args): void
    {
        $em = $args->getObjectManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            if (!$entity instanceof SluggableInterface) {
                continue;
            }

            $changeSet = $uow->getEntityChangeSet($entity);

            $slugChange = $changeSet['slug'] ?? null;
            if (!\is_array($slugChange) || 2 !== \count($slugChange)) {
                continue;
            }

            $oldSlug = \is_string($slugChange[0] ?? null) ? mb_trim($slugChange[0]) : '';
            $newSlug = \is_string($slugChange[1] ?? null) ? mb_trim($slugChange[1]) : '';

            if ('' === $oldSlug || '' === $newSlug || $oldSlug === $newSlug) {
                continue;
            }

            $id = $entity->getId();

            if ($id instanceof Uuid) {
                $entityId = $id->toRfc4122(); // string uuid
            } else {
                $entityId = (string) $id; // string numeric
            }

            $history = SlugHistory::record(
                oldSlug: $oldSlug,
                entityClass: $entity::class,
                entityId: $entityId
            );

            $em->persist($history);

            $meta = $em->getClassMetadata(SlugHistory::class);
            $uow->computeChangeSet($meta, $history);
        }
    }
}
