<?php

namespace App\Repository;

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

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

    /**
     * Nombre de codes générés pour cet email depuis $since (rate limiting applicatif).
     */
    public function countRecentForEmail(string $email, \DateTimeImmutable $since): int
    {
        return (int) $this->createQueryBuilder('o')
            ->select('COUNT(o.id)')
            ->andWhere('o.email = :email')
            ->andWhere('o.createdAt > :since')
            ->setParameter('email', $email)
            ->setParameter('since', $since)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Dernier code non utilisé et non expiré pour cet email.
     */
    public function findLatestValid(string $email, \DateTimeImmutable $now): ?OtpCode
    {
        return $this->createQueryBuilder('o')
            ->andWhere('o.email = :email')
            ->andWhere('o.expiresAt > :now')
            ->andWhere('o.used = false')
            ->setParameter('email', $email)
            ->setParameter('now', $now)
            ->orderBy('o.createdAt', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * Supprime les codes antérieurs à $before pour cet email (purge des anciens).
     */
    public function deleteOlderThan(string $email, \DateTimeImmutable $before): void
    {
        $this->createQueryBuilder('o')
            ->delete()
            ->andWhere('o.email = :email')
            ->andWhere('o.createdAt < :before')
            ->setParameter('email', $email)
            ->setParameter('before', $before)
            ->getQuery()
            ->execute();
    }

    public function deleteAllForEmail(string $email): void
    {
        $this->createQueryBuilder('o')
            ->delete()
            ->andWhere('o.email = :email')
            ->setParameter('email', $email)
            ->getQuery()
            ->execute();
    }
}
