<?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\CustomFieldsBundle\EntityRepository\CustomFieldLongChoice;

use Chill\CustomFieldsBundle\Entity\CustomFieldLongChoice\Option;
use Doctrine\ORM\EntityRepository;

class OptionRepository extends EntityRepository
{
    /**
     * @param string $key
     *
     * @return Option[]
     */
    public function findFilteredByKey($key, mixed $includeParents = true, mixed $active = true)
    {
        $qb = $this->createQueryBuilder('option');
        $qb->where('option.key = :key');

        if (true === $active) {
            $qb->andWhere('option.active = true');
        }

        if (false === $includeParents) {
            $qb->andWhere('option.parent IS NOT NULL');

            if (true === $active) {
                $qb->join('option.parent', 'p');
                $qb->andWhere('p.active = true');
            }
        }

        $qb->setParameter('key', $key);

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

    /**
     * @return string[]
     */
    public function getKeys()
    {
        $keys = $this->createQueryBuilder('option')
            ->select('option.key')
            ->distinct()
            ->getQuery()
            ->getScalarResult();

        return array_map(static fn ($r) => $r['key'], $keys);
    }
}
