<?php

/*
 * This file is part of the Serenity 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 Serenity\CoreBundle\Seed\Doctrine\Repository;

use Doctrine\Persistence\ManagerRegistry;
use Serenity\CoreBundle\Seed\Entity\SeedState;
use Serenity\CoreBundle\Shared\Doctrine\Repository\BaseRepository;

final class SeedStateRepository extends BaseRepository
{
    private const string ENTITY_CLASS = SeedState::class;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, self::ENTITY_CLASS);
    }

    public function findOneBySaasAndSeed(?string $saasIdentifier, string $seedName): ?SeedState
    {
        $qb = $this->createQueryBuilder('s')
            ->andWhere('s.seedName = :seedName')
            ->setParameter('seedName', $seedName)
            ->setMaxResults(1);

        if (null === $saasIdentifier) {
            $qb->andWhere('s.saasIdentifier IS NULL');
        } else {
            $qb->andWhere('s.saasIdentifier = :saasIdentifier')
                ->setParameter('saasIdentifier', $saasIdentifier);
        }

        return $qb->getQuery()->getOneOrNullResult();
    }
}
