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

use Chill\DocStoreBundle\GenericDoc\FetchQueryToSqlBuilder;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocumentRepository;
use Chill\PersonBundle\Service\GenericDoc\Providers\AccompanyingPeriodWorkEvaluationGenericDocProvider;
use Doctrine\ORM\EntityManagerInterface;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;

/**
 * @internal
 *
 * @coversNothing
 */
class AccompanyingPeriodWorkEvaluationGenericDocProviderTest extends KernelTestCase
{
    use ProphecyTrait;
    private EntityManagerInterface $entityManager;

    private AccompanyingPeriodWorkEvaluationDocumentRepository $repository;

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

    /**
     * @dataProvider provideSearchArguments
     */
    public function testBuildFetchQueryForAccompanyingPeriod(
        ?\DateTimeImmutable $startDate = null,
        ?\DateTimeImmutable $endDate = null,
        ?string $content = null,
    ): void {
        $period = $this->entityManager->createQuery('SELECT a FROM '.AccompanyingPeriod::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $period) {
            throw new \RuntimeException('no accompanying period in databasee');
        }

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

        $provider = new AccompanyingPeriodWorkEvaluationGenericDocProvider(
            $security->reveal(),
            $this->entityManager,
            $this->repository,
        );

        $query = $provider->buildFetchQueryForAccompanyingPeriod($period, $startDate, $endDate, $content);
        ['sql' => $sql, 'params' => $params, 'types' => $types] = (new FetchQueryToSqlBuilder())->toSql($query);

        $nb = $this->entityManager->getConnection()->executeQuery(
            'SELECT COUNT(*) FROM ('.$sql.') AS sq',
            $params,
            $types
        )->fetchOne();

        self::assertIsInt($nb, 'Test that there are no errors');
    }

    public static function provideSearchArguments(): iterable
    {
        yield [null, null, null];
        yield [new \DateTimeImmutable('1 month ago'), null, null];
        yield [new \DateTimeImmutable('1 month ago'), new \DateTimeImmutable('now'), null];
        yield [null, null, 'test'];
    }
}
