<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Repository;

use App\Entity\User;
use App\Entity\WebAuthnCredential;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * Class WebAuthnCredentialRepository
 *
 * @package  App\Repository
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 12.
 *
 * @extends ServiceEntityRepository<WebAuthnCredential>
 *
 * @method WebAuthnCredential|null find($id, $lockMode = null, $lockVersion = null)
 * @method WebAuthnCredential|null findOneBy(array $criteria, array $orderBy = null)
 * @method WebAuthnCredential[]    findAll()
 * @method WebAuthnCredential[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class WebAuthnCredentialRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, WebAuthnCredential::class);
    }

    public function findByUser(User $user): array
    {
        return $this->findBy(['user' => $user], ['createdAt' => 'DESC']);
    }

    public function countByUser(User $user): int
    {
        return $this->count(['user' => $user]);
    }

    public function deleteByIdAndUser(int $id, User $user): void
    {
        $qb = $this->createQueryBuilder('wac');

        $qb
            ->delete()
            ->where($qb->expr()->eq('wac.id', ':id'))
            ->andWhere($qb->expr()->eq('wac.user', ':user'))
            ->setParameter('id', $id)
            ->setParameter('user', $user)
            ->getQuery()
            ->execute();
    }
}
