<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\EventListener\Doctrine\Offer;

use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
use Ferienpass\CoreBundle\Attribute\AsOfferEntityListener;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Symfony\Component\String\Slugger\SluggerInterface;

/**
 * Keeps every offer's alias in sync with its name on every write.
 *
 * The alias is only the human-readable tail of the canonical public URL
 * (/o/{edition}/{base58-uuid}-{alias}); the base58 UUID is the stable,
 * unique lookup key, so the alias needs neither uniqueness nor stability.
 */
#[AsOfferEntityListener(event: Events::prePersist)]
#[AsOfferEntityListener(event: Events::preUpdate)]
class AliasListener
{
    public function __construct(private readonly SluggerInterface $slugger)
    {
    }

    public function prePersist(OfferInterface $offer): void
    {
        $offer->generateAlias($this->slugger);
    }

    public function preUpdate(OfferInterface $offer, PreUpdateEventArgs $args): void
    {
        $old = $offer->getAlias();
        $offer->generateAlias($this->slugger);

        // A property mutated inside preUpdate is not in the already-computed
        // change set; recompute so the new alias is actually written.
        if ($offer->getAlias() !== $old) {
            $em = $args->getObjectManager();
            $em->getUnitOfWork()->recomputeSingleEntityChangeSet(
                $em->getClassMetadata($offer::class),
                $offer,
            );
        }
    }
}
