<?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\AdminBundle\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * The base58-UUID migration gives each admin route a parallel
 * `{name}_legacy` route (RFC4122) so old links keep resolving. But some
 * controllers branch on the route name — e.g. OfferEditController compares
 * `_canonical_route` (falling back to `_route`) against 'admin_offers_copy',
 * 'admin_offers_new_variant', etc. to decide copy/variant/edit behaviour. A
 * `_legacy` hit would carry '..._legacy' and silently miss those branches.
 *
 * This listener strips the '_legacy' suffix into `_canonical_route`, so every
 * legacy route behaves identically to its canonical counterpart for any code
 * that reads `_canonical_route`. Runs after the router (which sets `_route`).
 */
#[AsEventListener(event: KernelEvents::REQUEST, priority: 8)]
final class LegacyRouteCanonicalListener
{
    private const SUFFIX = '_legacy';

    public function __invoke(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $route = $request->attributes->get('_route');

        if (!\is_string($route) || !str_starts_with($route, 'admin_') || !str_ends_with($route, self::SUFFIX)) {
            return;
        }

        if (!$request->attributes->has('_canonical_route')) {
            $request->attributes->set('_canonical_route', substr($route, 0, -\strlen(self::SUFFIX)));
        }
    }
}
