<?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\Commerce\Catalog\Enrollment\Repository;

use CpCreation\VitiCore\Commerce\Catalog\Enrollment\Model\CatalogEnrollmentRequest;
use CpCreation\VitiCore\Commerce\Catalog\Enrollment\Model\CatalogEnrollmentStatus;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\UuidInterface;

/**
 * @extends ServiceEntityRepository<CatalogEnrollmentRequest>
 */
final class CatalogEnrollmentRequestRepository extends ServiceEntityRepository implements CatalogEnrollmentRequestStore
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, CatalogEnrollmentRequest::class);
    }

    public function findOneByRequestId(UuidInterface|string $requestId): ?CatalogEnrollmentRequest
    {
        return $this->findOneBy(['requestId' => $requestId]);
    }

    public function existsForFingerprint(string $configurationFingerprint): bool
    {
        return 0 < (int) $this->createQueryBuilder('request')
            ->select('COUNT(request.id)')
            ->andWhere('request.configurationFingerprint = :fingerprint')
            ->setParameter('fingerprint', $configurationFingerprint)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * @return list<CatalogEnrollmentRequest>
     */
    public function findUnprepared(int $limit): array
    {
        return $this->createQueryBuilder('request')
            ->andWhere('request.configurationFingerprint IS NULL')
            ->andWhere('request.status = :status')
            ->setParameter('status', CatalogEnrollmentStatus::PENDING)
            ->orderBy('request.id', 'ASC')
            ->setMaxResults(max(1, min(100, $limit)))
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<CatalogEnrollmentRequest>
     */
    public function findReadyForDelivery(\DateTimeImmutable $staleQueuedBefore, int $limit): array
    {
        return $this->createQueryBuilder('request')
            ->andWhere('request.configurationFingerprint IS NOT NULL')
            ->andWhere('(request.status = :pending OR (request.status = :queued AND request.lastQueuedAt <= :staleQueuedBefore))')
            ->setParameter('pending', CatalogEnrollmentStatus::PENDING)
            ->setParameter('queued', CatalogEnrollmentStatus::QUEUED)
            ->setParameter('staleQueuedBefore', $staleQueuedBefore)
            ->orderBy('request.id', 'ASC')
            ->setMaxResults(max(1, min(100, $limit)))
            ->getQuery()
            ->getResult();
    }

    public function findLatestRegistered(UuidInterface|string $instanceId): ?CatalogEnrollmentRequest
    {
        return $this->createQueryBuilder('request')
            ->andWhere('request.instanceId = :instanceId')
            ->andWhere('request.status = :status')
            ->setParameter('instanceId', $instanceId)
            ->setParameter('status', CatalogEnrollmentStatus::REGISTERED)
            ->orderBy('request.registeredAt', 'DESC')
            ->addOrderBy('request.id', 'DESC')
            ->setMaxResults(1)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
