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

use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\RequestStack;

final readonly class DocGeneratorTemplateRepository implements DocGeneratorTemplateRepositoryInterface
{
    private EntityRepository $repository;

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

    public function countByEntity(string $entity): int
    {
        $builder = $this->repository->createQueryBuilder('t');

        $builder
            ->select('count(t)')
            ->where('t.entity LIKE :entity')
            ->andWhere($builder->expr()->eq('t.active', "'TRUE'"))
            ->setParameter('entity', addslashes($entity));

        return $builder->getQuery()->getSingleScalarResult();
    }

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

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

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

    /**
     * @return array|DocGeneratorTemplate[]
     */
    public function findByEntity(string $entity, ?int $start = 0, ?int $limit = 50): array
    {
        $builder = $this->repository->createQueryBuilder('t');

        $builder
            ->where('t.entity LIKE :entity')
            ->andWhere($builder->expr()->eq('t.active', "'TRUE'"))
            ->setParameter('entity', addslashes($entity))
            ->addSelect('JSON_EXTRACT(t.name, :lang) AS HIDDEN name_lang')
            ->setParameter('lang', $this->requestStack->getCurrentRequest()->getLocale())
            ->addOrderBy('name_lang', 'ASC');

        return $builder
            ->getQuery()
            ->setFirstResult($start)
            ->setMaxResults($limit)
            ->getResult();
    }

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

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