<?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;

use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\PersonPhone;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ObjectRepository;
use libphonenumber\PhoneNumber;

class PersonRepository implements ObjectRepository
{
    private readonly EntityRepository $repository;

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

    /**
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     *
     * @deprecated
     */
    public function countByPhone(
        string $phonenumber,
        $centers,
        array $only = ['mobile', 'phone'],
    ): int {
        $qb = $this->repository->createQueryBuilder('p');
        $qb->select('COUNT(p)');

        $this->addByCenters($qb, $centers);
        $this->addPhoneNumber($qb, $phonenumber, $only);

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

    public function createQueryBuilder(string $alias, ?string $indexBy = null): QueryBuilder
    {
        return $this->repository->createQueryBuilder($alias, $indexBy);
    }

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

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

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

    public function findByIds($ids): array
    {
        return $this->repository->findBy(['id' => $ids]);
    }

    /**
     * @throws \Exception
     *
     * @deprecated Use @see{self::findByPhoneNumber} or use a dedicated method in PersonACLAwareRepository
     */
    public function findByPhone(
        string $phonenumber,
        $centers,
        $firstResult,
        $maxResults,
        array $only = ['mobile', 'phone'],
    ) {
        $qb = $this->repository->createQueryBuilder('p');
        $qb->select('p');

        $this->addByCenters($qb, $centers);
        $this->addPhoneNumber($qb, $phonenumber, $only);

        $qb->setFirstResult($firstResult)
            ->setMaxResults($maxResults);

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

    /**
     * Find a person which is associated to the given phonenumber, without restrictions
     * on any.
     *
     * @return list<Person>
     */
    public function findByPhoneNumber(PhoneNumber $phoneNumber, int $firstResult = 0, int $maxResults = 50): array
    {
        $qb = $this->repository->createQueryBuilder('p');
        $qb->select('p');

        $this->searchByPhoneNumbers($qb, $phoneNumber);

        $qb->setFirstResult($firstResult)
            ->setMaxResults($maxResults);

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

    public function findOneBy(array $criteria)
    {
        return $this->repository->findOneBy($criteria);
    }

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

    private function addByCenters(QueryBuilder $qb, array $centers): void
    {
        if (\count($centers) > 0) {
            $qb->andWhere($qb->expr()->in('p.center', ':centers'));
            $qb->setParameter('centers', $centers);
        }
    }

    private function searchByPhoneNumbers(QueryBuilder $qb, PhoneNumber $phoneNumber): void
    {
        $qb->setParameter('number', $phoneNumber, 'phone_number');

        $orX = $qb->expr()->orX();
        $orX->add($qb->expr()->eq('p.mobilenumber', ':number'));
        $orX->add($qb->expr()->eq('p.phonenumber', ':number'));
        $orX->add(
            $qb->expr()->exists('SELECT 1 FROM '.PersonPhone::class.' k WHERE k.phonenumber = :number AND k.person = p')
        );

        $qb->andWhere($orX);
    }

    /**
     * @throws \Exception
     */
    private function addPhoneNumber(QueryBuilder $qb, string $phonenumber, array $only): void
    {
        if (0 === \count($only)) {
            throw new \Exception('No array field to search');
        }

        $phonenumber = $this->parsePhoneNumber($phonenumber);

        $orX = $qb->expr()->orX();

        if (\in_array('mobile', $only, true)) {
            $orX->add($qb->expr()->like("REPLACE(p.mobilenumber, ' ', '')", ':phonenumber'));
        }

        if (\in_array('phone', $only, true)) {
            $orX->add($qb->expr()->like("REPLACE(p.phonenumber, ' ', '')", ':phonenumber'));
        }

        $qb->andWhere($orX);

        $qb->setParameter('phonenumber', '%'.$phonenumber.'%');
    }

    private function parsePhoneNumber(string $phonenumber): string
    {
        return \str_replace(' ', '', $phonenumber);
    }
}
