<?php

namespace App\ClinicService\Repository;

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

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

    /** @return ServiceItemRelation[] */
    public function findForItem(ServiceItem $item): array
    {
        return $this->createQueryBuilder('r')
            ->where('r.item = :item')
            ->setParameter('item', $item)
            ->getQuery()
            ->getResult();
    }

    /**
     * همهٔ روابطی که یک سرِ آن‌ها در این مجموعه است — یک کوئری برای کل اعتبارسنجی.
     *
     * @param int[] $itemIds
     * @return ServiceItemRelation[]
     */
    public function findTouching(array $itemIds): array
    {
        if ($itemIds === []) {
            return [];
        }

        return $this->createQueryBuilder('r')
            ->where('r.item IN (:ids) OR r.relatedItem IN (:ids)')
            ->setParameter('ids', $itemIds)
            ->getQuery()
            ->getResult();
    }

    public function deleteForItem(ServiceItem $item): int
    {
        return (int) $this->createQueryBuilder('r')
            ->delete()
            ->where('r.item = :item')
            ->setParameter('item', $item)
            ->getQuery()
            ->execute();
    }
}
