<?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\Marketing\Repository;

use CpCreation\VitiCore\Marketing\Model\ReviewInvitation;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findOneByToken(string $token): ?ReviewInvitation
    {
        return $this->createQueryBuilder('invitation')
            ->addSelect('cart', 'items', 'variant', 'product')
            ->innerJoin('invitation.cart', 'cart')
            ->leftJoin('cart.items', 'items')
            ->leftJoin('items.variant', 'variant')
            ->leftJoin('variant.product', 'product')
            ->andWhere('(invitation.tokenHash = :tokenHash OR invitation.reminderTokenHash = :tokenHash)')
            ->setParameter('tokenHash', hash('sha256', $token))
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @return list<ReviewInvitation>
     */
    public function findDueForSecondReminder(
        \DateTimeImmutable $sentBefore,
        \DateTimeImmutable $now,
        \DateTimeImmutable $staleQueuedBefore,
        int $limit,
    ): array {
        return $this->createQueryBuilder('invitation')
            ->andWhere('invitation.status = :status')
            ->andWhere('invitation.sentAt IS NOT NULL')
            ->andWhere('invitation.sentAt <= :sentBefore')
            ->andWhere('invitation.expiresAt > :now')
            ->andWhere('invitation.reminderSentAt IS NULL')
            ->andWhere('invitation.reminderSuppressedAt IS NULL')
            ->andWhere('invitation.reminderQueuedAt IS NULL OR invitation.reminderQueuedAt <= :staleQueuedBefore')
            ->setParameter('status', ReviewInvitation::STATUS_SENT)
            ->setParameter('sentBefore', $sentBefore)
            ->setParameter('now', $now)
            ->setParameter('staleQueuedBefore', $staleQueuedBefore)
            ->orderBy('invitation.sentAt', 'ASC')
            ->setMaxResults(max(1, min(250, $limit)))
            ->getQuery()
            ->getResult();
    }
}
