<?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\AdminBundle\Components;

use Contao\CoreBundle\Repository\WebauthnCredentialRepository;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\WebauthnUserEntityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;

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

    /**
     * @return list<\Contao\CoreBundle\Entity\WebauthnCredential>
     */
    #[ExposeInTemplate]
    public function passkeys(): array
    {
        $user = $this->currentUser();
        if (!$user instanceof User) {
            return [];
        }

        $entity = $this->userEntities->findOneByUsername($user->getUsername());

        return null !== $entity ? array_values($this->credentials->findAllForUserEntity($entity)) : [];
    }

    #[ExposeInTemplate]
    public function passwordless(): bool
    {
        $user = $this->currentUser();

        return $user instanceof User && null === $user->getPassword();
    }

    private function currentUser(): ?User
    {
        $user = $this->getUser();

        return $user instanceof User ? $user : null;
    }
}
