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

use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\Relationships\Relationship;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ObjectRepository;

class RelationshipRepository implements ObjectRepository
{
    private readonly EntityManagerInterface $em;

    private readonly EntityRepository $repository;

    public function __construct(EntityManagerInterface $em)
    {
        $this->repository = $em->getRepository(Relationship::class);
        $this->em = $em;
    }

    public function countByPerson(Person $person): int
    {
        return $this->buildQueryByPerson($person)
            ->select('COUNT(p)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function find($id): ?Relationship
    {
        return $this->repository->find($id);
    }

    public function findAll(): array
    {
        return $this->repository->findAll();
    }

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

    /**
     * @return array|Relationship[]
     */
    public function findByPerson(Person $person): array
    {
        return $this->buildQueryByPerson($person)
            ->select('r')
            ->getQuery()
            ->getResult();
    }

    public function findOneBy(array $criteria): ?Relationship
    {
        return $this->findOneBy($criteria);
    }

    public function getClassName(): string
    {
        return Relationship::class;
    }

    private function buildQueryByPerson(Person $person): QueryBuilder
    {
        $qb = $this->em->createQueryBuilder();
        $qb
            ->from(Relationship::class, 'r')
            ->where(
                $qb->expr()->orX(
                    $qb->expr()->eq('r.fromPerson', ':person'),
                    $qb->expr()->eq('r.toPerson', ':person')
                )
            )
            ->setParameter('person', $person);

        return $qb;
    }
}
