<?php

namespace App\ClinicService\Repository;

use App\ClinicService\Entity\CatalogCategory;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<CatalogCategory>
 */
class CatalogCategoryRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, CatalogCategory::class);
    }

    public function findByUuid(string $uuid): ?CatalogCategory
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /**
     * کل درخت یک محیط با **یک** کوئری؛ ساختار درختی در PHP بسته می‌شود، نه با یک
     * کوئری per گره.
     *
     * @return CatalogCategory[]
     */
    public function findForPair(string $entityType, int $entityId): array
    {
        return $this->createQueryBuilder('c')
            ->where('c.entityType = :type')
            ->andWhere('c.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('c.sortOrder', 'ASC')
            ->addOrderBy('c.name', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function countChildren(CatalogCategory $category): int
    {
        return (int) $this->createQueryBuilder('c')
            ->select('COUNT(c.id)')
            ->where('c.parent = :parent')
            ->setParameter('parent', $category)
            ->getQuery()
            ->getSingleScalarResult();
    }
}
