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

use Contao\CoreBundle\ContaoCoreBundle;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;

final class WebauthnFrontendScopeListener
{
    private const FRONTEND_WEBAUTHN_PATHS = [
        '/assertion/options',
        '/assertion/result',
        '/passkey/options',
        '/passkey/result',
    ];

    #[AsEventListener(priority: 9)]
    public function __invoke(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();

        if ($request->attributes->has('_scope')) {
            return;
        }

        if (!\in_array($request->getPathInfo(), self::FRONTEND_WEBAUTHN_PATHS, true)) {
            return;
        }

        $request->attributes->set('_scope', ContaoCoreBundle::SCOPE_FRONTEND);
    }
}
