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

use Chill\PersonBundle\Entity\AccompanyingPeriod\ClosingMotive;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

final readonly class ClosingMotiveRepository implements ClosingMotiveRepositoryInterface
{
    private EntityRepository $repository;

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

    public function find($id): ?ClosingMotive
    {
        return $this->repository->find($id);
    }

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

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

    public function findOneBy(array $criteria): ?ClosingMotive
    {
        return $this->findOneBy($criteria);
    }

    public function getActiveClosingMotive(bool $onlyLeaf = true)
    {
        $rsm = new ResultSetMappingBuilder($this->entityManager);
        $rsm->addRootEntityFromClassMetadata($this->repository->getClassName(), 'cm');

        $sql = 'SELECT '.(string) $rsm.'
            FROM chill_person_accompanying_period_closingmotive AS cm
            WHERE
                active IS TRUE ';

        if ($onlyLeaf) {
            $sql .= 'AND cm.id NOT IN (
                SELECT DISTINCT parent_id FROM chill_person_accompanying_period_closingmotive WHERE parent_id IS NOT NULL
            )';
        }

        $sql .= ' ORDER BY cm.ordering ASC';

        return $this
            ->entityManager
            ->createNativeQuery($sql, $rsm)
            ->getResult();
    }

    public function getClassName(): string
    {
        return ClosingMotive::class;
    }
}
