<?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\Controller\Fragment;

use Contao\CoreBundle\Repository\WebauthnCredentialRepository;
use Ferienpass\CoreBundle\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\WebauthnUserEntityRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;

final class PasskeysController extends AbstractPrivateFragmentController
{
    public function __construct(
        private readonly WebauthnUserEntityRepository $userEntities,
        #[Autowire(service: 'contao.repository.webauthn_credential')]
        private readonly WebauthnCredentialRepository $credentials,
    ) {
    }

    public function __invoke(): Response
    {
        $user = $this->getUser();
        if (!$user instanceof User) {
            return new Response('', Response::HTTP_NO_CONTENT);
        }

        $userEntity = $this->userEntities->findOneByUsername($user->getUsername());
        $passkeys = null !== $userEntity ? $this->credentials->findAllForUserEntity($userEntity) : [];

        return $this->render('@Contao/fragment/user_account/passkeys.html.twig', [
            'passkeys' => $passkeys,
            'passwordless' => null === $user->getPassword(),
            'hasPassword' => null !== $user->getPassword(),
            'magicLinksDisabled' => $user->isMagicLinksDisabled(),
        ]);
    }
}
