<?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\Entity\WebauthnCredential;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\HttpFoundation\RequestStack;

#[AsEntityListener(event: Events::prePersist, entity: WebauthnCredential::class)]
final class WebauthnCredentialNamer
{
    public const SESSION_KEY = 'account.passkey_name';

    public function __construct(private readonly RequestStack $requestStack)
    {
    }

    public function prePersist(WebauthnCredential $credential, PrePersistEventArgs $args): void
    {
        if ('' !== $credential->name) {
            return;
        }

        try {
            $session = $this->requestStack->getSession();
        } catch (\Throwable) {
            return;
        }

        $name = trim((string) $session->get(self::SESSION_KEY, ''));
        if ('' !== $name) {
            $credential->name = mb_substr($name, 0, 64);
            $session->remove(self::SESSION_KEY);
        }
    }
}
