<?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 Service\GenericDoc\Providers;

use Chill\CalendarBundle\Service\GenericDoc\Providers\PersonCalendarGenericDocProvider;
use Chill\DocStoreBundle\GenericDoc\FetchQueryToSqlBuilder;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;

/**
 * @internal
 *
 * @coversNothing
 */
class PersonCalendarGenericDocProviderTest extends KernelTestCase
{
    private Security $security;

    private EntityManagerInterface $entityManager;

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

    /**
     * @dataProvider provideDataForPerson
     */
    public function testBuildFetchQueryForPerson(Person $person, ?\DateTimeImmutable $startDate, ?\DateTimeImmutable $endDate, ?string $content): void
    {
        $provider = new PersonCalendarGenericDocProvider($this->security, $this->entityManager);

        $query = $provider->buildFetchQueryForPerson($person, $startDate, $endDate, $content);

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

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

        self::assertIsInt($nb);
    }

    public static function provideDataForPerson(): iterable
    {
        self::bootKernel();
        $entityManager = self::getContainer()->get(EntityManagerInterface::class);

        if (null === $person = $entityManager->createQuery('SELECT p FROM '.Person::class.' p ')
            ->setMaxResults(1)->getSingleResult()) {
            throw new \RuntimeException('There is no person');
        }

        yield [$person, null, null, null];
        yield [$person, new \DateTimeImmutable('1 year ago'), null, null];
        yield [$person, new \DateTimeImmutable('1 year ago'), new \DateTimeImmutable('6 month ago'), null];
        yield [$person, new \DateTimeImmutable('1 year ago'), new \DateTimeImmutable('6 month ago'), 'text'];
        yield [$person, null, null, 'text'];
        yield [$person, null, new \DateTimeImmutable('6 month ago'), null];
    }
}
