<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Repository;

use Chill\MainBundle\Entity\Regroupment;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;

final readonly class RegroupmentRepository implements RegroupmentRepositoryInterface
{
    private EntityRepository $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(Regroupment::class);
    }

    public function find($id, $lockMode = null, $lockVersion = null): ?Regroupment
    {
        return $this->repository->find($id, $lockMode, $lockVersion);
    }

    /**
     * @return Regroupment[]
     */
    public function findAll(): array
    {
        return $this->repository->findAll();
    }

    public function findAllActive(): array
    {
        return $this->repository->findBy(['isActive' => true], ['name' => 'ASC']);
    }

    /**
     * @param mixed|null $limit
     * @param mixed|null $offset
     *
     * @return Regroupment[]
     */
    public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null): array
    {
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
    }

    public function findOneBy(array $criteria, ?array $orderBy = null): ?Regroupment
    {
        return $this->repository->findOneBy($criteria, $orderBy);
    }

    /**
     * @throws NonUniqueResultException
     * @throws NoResultException
     */
    public function findOneByName(string $name): ?Regroupment
    {
        return $this->repository->createQueryBuilder('r')
            ->where('LOWER(r.name) = LOWER(:searched)')
            ->setParameter('searched', $name)
            ->getQuery()
            ->getSingleResult();
    }

    /**
     * @return array<Regroupment>
     */
    public function findRegroupmentAssociatedToNoCenter(): array
    {
        return $this->repository->createQueryBuilder('r')
            ->where('SIZE(r.centers) = 0')
            ->getQuery()
            ->getResult();
    }

    public function getClassName()
    {
        return Regroupment::class;
    }
}
