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

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Repository\AssociatedEntityToStoredObjectInterface;
use Chill\TicketBundle\Entity\Motive;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @template-extends ServiceEntityRepository<Motive>
 */
class MotiveRepository extends ServiceEntityRepository implements AssociatedEntityToStoredObjectInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Motive::class);
    }

    public function findAssociatedEntityToStoredObject(StoredObject $storedObject): ?Motive
    {
        $query = $this->createQueryBuilder('m');
        $query->select('m')
            ->where(':stored_object MEMBER OF m.storedObjects')
            ->setParameter('stored_object', $storedObject)
            ->setMaxResults(1)
        ;

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

    /**
     * @return list<Motive>
     */
    public function findByLabel(string $label, string $lang): array
    {
        $query = $this->createQueryBuilder('m');
        $query->select('m')
            ->where($query->expr()->like('JSON_EXTRACT(m.label, :lang)', ':label'))
            ->setParameter('label', $label)
            ->setParameter('lang', $lang);

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