<?php


namespace AutoAdmin\Bundle\Seo\EventListener;


use AutoAdmin\Bundle\Seo\Entity\Redirect;
use AutoAdmin\Bundle\Seo\Repository\RedirectRepository;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;

class RedirectEventListener
{
    private ManagerRegistry $doctrine;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $this->searchMatchingRedirect($event);
    }

    protected function searchMatchingRedirect(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();
        $uri = $request->getRequestUri();

        if (
            stripos($uri, '/_wdt/') === 0
            || stripos($uri, '/admin/') === 0 // not ideal, would prefer to keep admin url modifiable
        ) {
            return;
        }

        // TODO: optimize speed by caching redirects data to avoid db query
        /** @var RedirectRepository $repo */
        $repo = $this->doctrine->getRepository(Redirect::class);
        /** @var Redirect|null $found */
        $found = $repo->contentFindOneBy(['_.origin' => $uri]);

        if (!$found) {
            $found = $repo->contentFindOneByOriginLike($uri);
            if (!$found) {
                return;
            }
        }

        $destination = $found->getDestination();
        // if destination has "**" (redirect multiple) as the end of slug
        if (substr($destination, -2) === '**') {
            $origin = str_replace('**', '', $found->getOrigin());

            // get end of origin URL to pass to destination
            $originEnd = substr($uri, stripos($uri, $origin) + strlen($origin));

            // add to destination
            $destination = str_replace('**', $originEnd, $destination);
        }

        $destination = $this->handleDestination($found, $uri);

        $found->setCounter($found->getCounter() + 1);
        $entityManager = $this->doctrine->getManager();
        $entityManager->persist($found);
        $entityManager->flush();

        $response = new RedirectResponse(
            $destination,
            $found->getType() ?: Response::HTTP_FOUND,
            ['X-Custom-Redirection' => '1']
        );

        $event->setResponse($response);
    }

    private function handleDestination(Redirect $found, string $uri): string
    {
        $destination = $found->getDestination();
        $origin = $found->getOrigin();
        // if destination has "**" (redirect multiple) as the end of slug
        if (substr($destination, -2) === '**') {
            $origin = str_replace('**', '', $origin);

            // get end of origin URL to pass to destination
            $originEnd = substr($uri, stripos($uri, $origin) + strlen($origin));

            // add to destination
            $destination = str_replace('**', $originEnd, $destination);
        }

        // Format regex
        $originRegex = preg_replace('#(\*[^*]+\*)#', '(.+)', $origin);
        $originRegex = str_replace('/', '\/', $originRegex);

        // Get matches with regex
        preg_match("#$originRegex#", $uri, $matches);

        // Assign matches to destination
        foreach ($matches as $key => $match) {
            $destination = str_replace("*$key*", $match, $destination);
        }

        return $destination;
    }

    public function onKernelException(RequestEvent $event): void
    {
        $this->searchMatchingRedirect($event);
    }
}
