<?php

declare(strict_types=1);

namespace External\ZNZBundle\EventSubscriber;

use KupShop\KupShopBundle\Event\NotFoundEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

class NotFoundSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            NotFoundEvent::class => [
                ['checkForFilterInUrl', 255],
            ],
        ];
    }

    /** Redirects URLs with filter to base URL */
    public function checkForFilterInUrl(NotFoundEvent $event): void
    {
        $uri = $event->getRequest()->getRequestUri();

        if (str_contains($uri, '/filter/') && !str_ends_with($uri, '/filter/')) {
            $parts = explode('/filter/', $uri);
            if (!empty($parts[0])) {
                $event->setResponse(
                    new RedirectResponse(rtrim($parts[0], '/').'.html')
                );
            }
        }
    }
}
