<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Mailer\Repository;

use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Mailer\Model\EmailLog;
use CpCreation\VitiCore\Repository\BaseRepository;
use CpCreation\VitiCore\User\Model\User;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @return list<EmailLog>
     */
    public function findRecentByCart(Cart $cart, int $limit = 20): array
    {
        return $this->createQueryBuilder('email_log')
            ->andWhere('email_log.cart = :cart')
            ->setParameter('cart', $cart)
            ->orderBy('email_log.queuedAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<EmailLog>
     */
    public function findRecentByUser(User $user, int $limit = 30): array
    {
        return $this->createQueryBuilder('email_log')
            ->andWhere('email_log.user = :user')
            ->setParameter('user', $user)
            ->orderBy('email_log.queuedAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
