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

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Repository\CenterRepositoryInterface;
use Chill\MainBundle\Repository\CountryRepository;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\PersonPhone;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Chill\PersonBundle\Repository\PersonACLAwareRepository;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\Attributes\DataProvider;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;

/**
 * @internal
 *
 * @coversNothing
 */
final class PersonACLAwareRepositoryTest extends KernelTestCase
{
    use ProphecyTrait;

    private CenterRepositoryInterface $centerRepository;

    private CountryRepository $countryRepository;

    private EntityManagerInterface $entityManager;

    private PersonIdentifierManagerInterface $personIdentifierManager;

    protected function setUp(): void
    {
        self::bootKernel();

        $this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
        $this->countryRepository = self::getContainer()->get(CountryRepository::class);
        $this->centerRepository = self::getContainer()->get(CenterRepositoryInterface::class);
        $this->personIdentifierManager = self::getContainer()->get(PersonIdentifierManagerInterface::class);

    }

    public function testCountByCriteria()
    {
        $user = new User();

        $authorizationHelper = $this->prophesize(AuthorizationHelperInterface::class);
        $authorizationHelper->getReachableCenters(Argument::exact($user), Argument::exact(PersonVoter::SEE))
            ->willReturn($this->centerRepository->findAll());

        $security = $this->prophesize(Security::class);
        $security->getUser()->willReturn($user);

        $repository = new PersonACLAwareRepository(
            $security->reveal(),
            $this->entityManager,
            $this->countryRepository,
            $authorizationHelper->reveal(),
            $this->personIdentifierManager,
        );

        $number = $repository->countBySearchCriteria('diallo');

        $this->assertGreaterThan(0, $number);
    }

    public function testFindByCriteria()
    {
        $user = new User();

        $authorizationHelper = $this->prophesize(AuthorizationHelperInterface::class);
        $authorizationHelper->getReachableCenters(Argument::exact($user), Argument::exact(PersonVoter::SEE))
            ->willReturn($this->centerRepository->findAll());

        $security = $this->prophesize(Security::class);
        $security->getUser()->willReturn($user);

        $repository = new PersonACLAwareRepository(
            $security->reveal(),
            $this->entityManager,
            $this->countryRepository,
            $authorizationHelper->reveal(),
            $this->personIdentifierManager,
        );

        $results = $repository->findBySearchCriteria(0, 5, false, 'diallo');

        $this->assertGreaterThan(0, \count($results));
        $this->assertContainsOnlyInstancesOf(Person::class, $results);

        foreach ($results as $person) {
            $this->assertStringContainsString('diallo', strtolower($person->getFirstName().' '.$person->getLastName()));
        }
    }

    /**
     * @dataProvider providePersonsWithPhoneNumbers
     */
    public function testFindByPhonenumber(\libphonenumber\PhoneNumber $phoneNumber, ?int $expectedId): void
    {
        $user = new User();

        $authorizationHelper = $this->prophesize(AuthorizationHelperInterface::class);
        $authorizationHelper->getReachableCenters(Argument::exact($user), Argument::exact(PersonVoter::SEE))
            ->willReturn($this->centerRepository->findAll());

        $security = $this->prophesize(Security::class);
        $security->getUser()->willReturn($user);

        $repository = new PersonACLAwareRepository(
            $security->reveal(),
            $this->entityManager,
            $this->countryRepository,
            $authorizationHelper->reveal(),
            $this->personIdentifierManager,
        );

        $actual = $repository->findByPhone($phoneNumber, 0, 10);

        if (null === $expectedId) {
            self::assertCount(0, $actual);
        } else {
            $actualIds = array_map(fn (Person $person) => $person->getId(), $actual);

            self::assertContains($expectedId, $actualIds);
        }
    }

    public static function providePersonsWithPhoneNumbers(): iterable
    {
        self::bootKernel();
        $em = self::getContainer()->get(EntityManagerInterface::class);
        $center = $em->createQuery('SELECT c FROM '.Center::class.' c ')->setMaxResults(1)
            ->getSingleResult();
        $util = \libphonenumber\PhoneNumberUtil::getInstance();

        $mobile = $util->parse('+32486123456');
        $fixed = $util->parse('+3281136917');
        $anotherMobile = $util->parse('+32486123478');
        $person = (new Person())->setFirstName('diallo')->setLastName('diallo')->setCenter($center);
        $person->setMobilenumber($mobile)->setPhonenumber($fixed);
        $otherPhone = new PersonPhone();
        $otherPhone->setPerson($person);
        $otherPhone->setPhonenumber($anotherMobile);
        $otherPhone->setType('mobile');

        $em->persist($person);
        $em->persist($otherPhone);

        $em->flush();

        self::ensureKernelShutdown();

        yield [$mobile, $person->getId()];
        yield [$anotherMobile, $person->getId()];
        yield [$fixed, $person->getId()];
        yield [$util->parse('+331234567890'), null];
    }
}
