<?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\Entity\ActivityType;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserJob;
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\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;

/**
 * @internal
 *
 * @coversNothing
 */
class ActivityACLAwareRepositoryTest extends KernelTestCase
{
    use ProphecyTrait;
    private AuthorizationHelperForCurrentUserInterface $authorizationHelperForCurrentUser;

    private CenterResolverManagerInterface $centerResolverManager;

    private ActivityRepository $activityRepository;

    private EntityManagerInterface $entityManager;

    private Security $security;

    private RequestStack $requestStack;

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

        $this->authorizationHelperForCurrentUser = self::getContainer()->get(AuthorizationHelperForCurrentUserInterface::class);
        $this->centerResolverManager = self::getContainer()->get(CenterResolverManagerInterface::class);
        $this->activityRepository = self::getContainer()->get(ActivityRepository::class);
        $this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
        $this->security = self::getContainer()->get(Security::class);

        $this->requestStack = $requestStack = new RequestStack();
        $request = $this->prophesize(Request::class);
        $request->getLocale()->willReturn('fr');
        $request->getDefaultLocale()->willReturn('fr');
        $requestStack->push($request->reveal());
    }

    /**
     * @dataProvider provideDataFindByAccompanyingPeriod
     */
    public function testFindByAccompanyingPeriod(AccompanyingPeriod $period, User $user, string $role, ?int $start = 0, ?int $limit = 1000, array $orderBy = ['date' => 'DESC'], array $filters = []): void
    {
        $security = $this->prophesize(Security::class);
        $security->isGranted($role, $period)->willReturn(true);
        $security->getUser()->willReturn($user);

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

        $actual = $repository->findByAccompanyingPeriod($period, $role, $start, $limit, $orderBy, $filters);

        self::assertIsArray($actual);
    }

    /**
     * @dataProvider provideDataFindByAccompanyingPeriod
     */
    public function testfindByAccompanyingPeriodSimplified(AccompanyingPeriod $period, User $user, string $role, ?int $start = 0, ?int $limit = 1000, array $orderBy = ['date' => 'DESC'], array $filters = []): void
    {
        $security = $this->prophesize(Security::class);
        $security->isGranted($role, $period)->willReturn(true);
        $security->getUser()->willReturn($user);

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

        $actual = $repository->findByAccompanyingPeriodSimplified($period);

        self::assertIsArray($actual);
    }

    /**
     * @dataProvider provideDataFindByAccompanyingPeriod
     */
    public function testFindActivityTypeByAccompanyingPeriod(AccompanyingPeriod $period, User $user, string $role, ?int $start = 0, ?int $limit = 1000, array $orderBy = ['date' => 'DESC'], array $filters = []): void
    {
        $security = $this->prophesize(Security::class);
        $security->isGranted($role, $period)->willReturn(true);
        $security->getUser()->willReturn($user);

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

        $actual = $repository->findActivityTypeByAssociated($period);

        self::assertIsArray($actual);
    }

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

        if (null === $period = $this->entityManager
            ->createQueryBuilder()
            ->select('a')
            ->from(AccompanyingPeriod::class, 'a')
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()) {
            throw new \RuntimeException('no period found');
        }

        if ([] === $types = $this->entityManager
            ->createQueryBuilder()
            ->select('t')
            ->from(ActivityType::class, 't')
            ->setMaxResults(2)
            ->getQuery()
            ->getResult()) {
            throw new \RuntimeException('no types');
        }

        if ([] === $jobs = $this->entityManager
            ->createQueryBuilder()
            ->select('j')
            ->from(UserJob::class, 'j')
            ->setMaxResults(2)
            ->getQuery()
            ->getResult()
        ) {
            $job = new UserJob();
            $job->setLabel(['fr' => 'test']);
            $this->entityManager->persist($job);
            $this->entityManager->flush();
        }

        if (null === $user = $this->entityManager
            ->createQueryBuilder()
            ->select('u')
            ->from(User::class, 'u')
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()
        ) {
            throw new \RuntimeException('no user found');
        }

        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], []];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['my_activities' => true]];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['types' => $types]];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['jobs' => $jobs]];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago')]];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['before' => new \DateTimeImmutable('1 year ago')]];
        yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago'), 'before' => new \DateTimeImmutable('1 month ago')]];
    }

    /**
     * @dataProvider provideDataFindByPerson
     */
    public function testFindActivityTypeByPerson(Person $person, User $user, array $centers, array $scopes, string $role, ?int $start = 0, ?int $limit = 1000, ?array $orderBy = [], array $filters = []): void
    {
        $role = ActivityVoter::SEE;
        $centerResolver = $this->prophesize(CenterResolverManagerInterface::class);
        $centerResolver->resolveCenters($person)->willReturn($centers);

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

        $security = $this->prophesize(Security::class);
        $security->isGranted($role, Argument::type(AccompanyingPeriod::class))->willReturn(true);
        $security->getUser()->willReturn($user);

        $repository = new ActivityACLAwareRepository(
            $authorizationHelper->reveal(),
            $centerResolver->reveal(),
            $this->activityRepository,
            $this->entityManager,
            $security->reveal(),
            $this->requestStack
        );

        $actual = $repository->findByPerson($person, $role, $start, $limit, $orderBy, $filters);

        self::assertIsArray($actual);
    }

    /**
     * @dataProvider provideDataFindByPerson
     */
    public function testFindByPerson(Person $person, User $user, array $centers, array $scopes, string $role, ?int $start = 0, ?int $limit = 1000, ?array $orderBy = [], array $filters = []): void
    {
        $centerResolver = $this->prophesize(CenterResolverManagerInterface::class);
        $centerResolver->resolveCenters($person)->willReturn($centers);

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

        $security = $this->prophesize(Security::class);
        $security->isGranted($role, Argument::type(AccompanyingPeriod::class))->willReturn(true);
        $security->getUser()->willReturn($user);

        $repository = new ActivityACLAwareRepository(
            $authorizationHelper->reveal(),
            $centerResolver->reveal(),
            $this->activityRepository,
            $this->entityManager,
            $security->reveal(),
            $this->requestStack
        );

        $actual = $repository->findByPerson($person, $role, $start, $limit, $orderBy, $filters);

        self::assertIsArray($actual);
    }

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

        /** @var Person $person */
        if (null === $person = $this->entityManager->createQueryBuilder()
            ->select('p')->from(Person::class, 'p')->setMaxResults(1)
            ->getQuery()->getSingleResult()) {
            throw new \RuntimeException('person not found');
        }

        /** @var AccompanyingPeriod $period1 */
        if (null === $period1 = $this->entityManager
            ->createQueryBuilder()
            ->select('a')
            ->from(AccompanyingPeriod::class, 'a')
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()) {
            throw new \RuntimeException('no period found');
        }

        /** @var AccompanyingPeriod $period2 */
        if (null === $period2 = $this->entityManager
            ->createQueryBuilder()
            ->select('a')
            ->from(AccompanyingPeriod::class, 'a')
            ->where('a.id > :pid')
            ->setParameter('pid', $period1->getId())
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()) {
            throw new \RuntimeException('no second period found');
        }
        // add a period
        $period1->addPerson($person);
        $period2->addPerson($person);
        $period1->getParticipationsContainsPerson($person)->first()->setEndDate(
            (new \DateTime('now'))->add(new \DateInterval('P1M'))
        );

        if ([] === $types = $this->entityManager
            ->createQueryBuilder()
            ->select('t')
            ->from(ActivityType::class, 't')
            ->setMaxResults(2)
            ->getQuery()
            ->getResult()) {
            throw new \RuntimeException('no types');
        }

        if ([] === $jobs = $this->entityManager
            ->createQueryBuilder()
            ->select('j')
            ->from(UserJob::class, 'j')
            ->setMaxResults(2)
            ->getQuery()
            ->getResult()
        ) {
            throw new \RuntimeException('no jobs found');
        }

        if (null === $user = $this->entityManager
            ->createQueryBuilder()
            ->select('u')
            ->from(User::class, 'u')
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult()
        ) {
            throw new \RuntimeException('no user found');
        }

        if ([] === $centers = $this->entityManager->createQueryBuilder()
            ->select('c')->from(Center::class, 'c')->setMaxResults(2)->getQuery()
            ->getResult()) {
            throw new \RuntimeException('no centers found');
        }

        if ([] === $scopes = $this->entityManager->createQueryBuilder()
            ->select('s')->from(Scope::class, 's')->setMaxResults(2)->getQuery()
            ->getResult()) {
            throw new \RuntimeException('no scopes found');
        }

        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], []];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['my_activities' => true]];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['types' => $types]];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['jobs' => $jobs]];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago')]];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['before' => new \DateTimeImmutable('1 year ago')]];
        yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago'), 'before' => new \DateTimeImmutable('1 month ago')]];
    }
}
