<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\TransactionalEmail\Repository;

use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\TransactionalEmail\Model\TransactionalEmail;
use CpCreation\VitiCore\TransactionalEmail\Model\TransactionalEmailQueue;
use Doctrine\Persistence\ManagerRegistry;

class TransactionalEmailQueueRepository extends BaseRepository
{
    /**
     * @throws \ReflectionException
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, TransactionalEmailQueue::class);
    }

    public function findExisting(TransactionalEmail $transactionalEmail, string $relatedType, string $relatedId): ?TransactionalEmailQueue
    {
        return $this->findOneBy([
            'transactionalEmail' => $transactionalEmail,
            'relatedType' => $relatedType,
            'relatedId' => $relatedId,
        ]);
    }

    /**
     * @return list<TransactionalEmailQueue>
     */
    public function findDuePending(\DateTimeImmutable $now, int $limit = 50): array
    {
        return $this->createQueryBuilder('queue')
            ->andWhere('queue.scheduledAt <= :now')
            ->andWhere('queue.sentAt IS NULL')
            ->andWhere('queue.skippedAt IS NULL')
            ->setParameter('now', $now)
            ->orderBy('queue.scheduledAt', 'ASC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
