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

use Chill\EventBundle\Repository\EventACLAwareRepository;
use Chill\EventBundle\Security\EventVoter;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperForCurrentUserInterface;
use Doctrine\ORM\EntityManagerInterface;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;

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

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

    /**
     * @dataProvider generateFilters
     *
     * @throws \Doctrine\ORM\NoResultException
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function testCountAllViewable(array $filters): void
    {
        $repository = $this->buildEventACLAwareRepository();

        $this->assertGreaterThanOrEqual(0, $repository->countAllViewable($filters));
    }

    /**
     * @dataProvider generateFilters
     */
    public function testFindAllViewable(array $filters): void
    {
        $repository = $this->buildEventACLAwareRepository();

        $this->assertIsArray($repository->findAllViewable($filters));
    }

    public static function generateFilters(): iterable
    {
        yield [[]];
    }

    public function buildEventACLAwareRepository(): EventACLAwareRepository
    {
        $em = self::getContainer()->get(EntityManagerInterface::class);
        $user = $em->createQuery('SELECT u FROM '.User::class.' u')
            ->setMaxResults(1)
            ->getSingleResult()
        ;

        $scopes = $em->createQuery('SELECT s FROM '.Scope::class.' s')
            ->setMaxResults(3)
            ->getResult();

        $centers = $em->createQuery('SELECT c FROM '.Center::class.' c')
            ->setMaxResults(3)
            ->getResult();

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

        $authorizationHelper = $this->prophesize(AuthorizationHelperForCurrentUserInterface::class);
        $authorizationHelper->getReachableCenters(EventVoter::SEE)->willReturn($centers);
        $authorizationHelper->getReachableScopes(EventVoter::SEE, Argument::type(Center::class))->willReturn($scopes);

        return new EventACLAwareRepository(
            $authorizationHelper->reveal(),
            $em,
            $security->reveal()
        );
    }
}
