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

use Chill\ActivityBundle\Repository\ActivityDocumentACLAwareRepository;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\DocStoreBundle\GenericDoc\FetchQueryToSqlBuilder;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperForCurrentUserInterface;
use Chill\MainBundle\Security\Resolver\CenterResolverManagerInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
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 ActivityDocumentACLAwareRepositoryTest extends KernelTestCase
{
    use ProphecyTrait;

    private EntityManagerInterface $entityManager;

    private CenterResolverManagerInterface $centerResolverManager;

    private AuthorizationHelperForCurrentUserInterface $authorizationHelperForCurrentUser;

    private Security $security;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
        $this->centerResolverManager = self::getContainer()->get(CenterResolverManagerInterface::class);
        $this->authorizationHelperForCurrentUser = self::getContainer()->get(AuthorizationHelperForCurrentUserInterface::class);
        $this->security = self::getContainer()->get(Security::class);
    }

    /**
     * @dataProvider provideDataForPerson
     */
    public function testBuildFetchQueryActivityDocumentLinkedToPersonFromPersonContext(Person $person, array $reachableScopes, bool $_unused, ?\DateTimeImmutable $startDate, ?\DateTimeImmutable $endDate, ?string $content): void
    {
        $authorizationHelper = $this->prophesize(AuthorizationHelperForCurrentUserInterface::class);
        $authorizationHelper->getReachableScopes(ActivityVoter::SEE, Argument::any())
            ->willReturn($reachableScopes);

        $repository = new ActivityDocumentACLAwareRepository(
            $this->entityManager,
            $this->centerResolverManager,
            $authorizationHelper->reveal(),
            $this->security
        );

        $query = $repository->buildFetchQueryActivityDocumentLinkedToPersonFromPersonContext($person, $startDate, $endDate, $content);
        ['sql' => $sql, 'params' => $params, 'types' => $types] = (new FetchQueryToSqlBuilder())->toSql($query);

        $nb = $this->entityManager->getConnection()->fetchOne("SELECT COUNT(*) FROM ({$sql}) sq", $params, $types);

        self::assertIsInt($nb);
    }

    /**
     * @dataProvider provideDataForPerson
     */
    public function testBuildFetchQueryActivityDocumentLinkedToAccompanyingPeriodFromPersonContext(Person $person, array $_unused, bool $canSeePeriod, ?\DateTimeImmutable $startDate, ?\DateTimeImmutable $endDate, ?string $content): void
    {
        $security = $this->prophesize(Security::class);
        $security->isGranted(ActivityVoter::SEE, Argument::type(AccompanyingPeriod::class))
            ->willReturn($canSeePeriod);

        $repository = new ActivityDocumentACLAwareRepository(
            $this->entityManager,
            $this->centerResolverManager,
            $this->authorizationHelperForCurrentUser,
            $security->reveal()
        );

        $query = $repository->buildFetchQueryActivityDocumentLinkedToAccompanyingPeriodFromPersonContext($person, $startDate, $endDate, $content);

        ['sql' => $sql, 'params' => $params, 'types' => $types] = (new FetchQueryToSqlBuilder())->toSql($query);

        $nb = $this->entityManager->getConnection()->fetchOne("SELECT COUNT(*) FROM ({$sql}) sq", $params, $types);

        self::assertIsInt($nb);
    }

    public function provideDataForPerson(): iterable
    {
        $this->setUp();

        if (null === $person = $this->entityManager->createQuery('SELECT p FROM '.Person::class.' p WHERE SIZE(p.accompanyingPeriodParticipations) > 0 ')
            ->setMaxResults(1)
            ->getSingleResult()) {
            throw new \RuntimeException('no person in dtabase');
        }

        if ([] === $scopes = $this->entityManager->createQuery('SELECT s FROM '.Scope::class.' s ')->setMaxResults(5)->getResult()) {
            throw new \RuntimeException('no scopes in database');
        }

        yield [$person, [], true, null, null, null];
        yield [$person, $scopes, true, null, null, null];
        yield [$person, $scopes, true, new \DateTimeImmutable('1 month ago'), null, null];
        yield [$person, $scopes, true, new \DateTimeImmutable('1 month ago'), new \DateTimeImmutable('1 week ago'), null];
        yield [$person, $scopes, true, new \DateTimeImmutable('1 month ago'), new \DateTimeImmutable('1 week ago'), 'content'];
        yield [$person, $scopes, true, null, new \DateTimeImmutable('1 week ago'), 'content'];
        yield [$person, [], true, new \DateTimeImmutable('1 month ago'), new \DateTimeImmutable('1 week ago'), 'content'];
    }
}
