<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Token;
use App\Enum\TokenType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<Token> */
class TokenRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Token::class);
    }

    public function findValidToken(string $uuid, TokenType $type): ?Token
    {
        return $this->createQueryBuilder('t')
            ->where('t.uuid = :uuid')
            ->andWhere('t.type = :type')
            ->andWhere('t.usedAt IS NULL')
            ->andWhere('t.expiresAt > :now')
            ->setParameter('uuid', $uuid)
            ->setParameter('type', $type)
            ->setParameter('now', new \DateTimeImmutable())
            ->getQuery()
            ->getOneOrNullResult();
    }
}
