<?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 Controller;

use Chill\MainBundle\Entity\NewsItem;
use Chill\MainBundle\Test\PrepareClientTrait;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class NewsItemsHistoryControllerTest extends WebTestCase
{
    use PrepareClientTrait;

    /**
     * @var list<array{0: class-string, 1: NewsItem}>
     */
    private static array $toDelete = [];

    public static function tearDownAfterClass(): void
    {
        self::bootKernel();
        $em = self::getContainer()->get(EntityManagerInterface::class);

        foreach (static::$toDelete as [$class, $entity]) {
            $query = $em->createQuery(sprintf('DELETE FROM %s e WHERE e.id = :id', $class))
                ->setParameter('id', $entity->getId());
            $query->execute();
        }

        static::$toDelete = [];

        self::ensureKernelShutdown();
    }

    protected function tearDown(): void
    {
        self::ensureKernelShutdown();
    }

    public function testList()
    {
        self::ensureKernelShutdown();
        $client = $this->getClientAuthenticated();

        $client->request('GET', '/fr/news-items/history');

        self::assertResponseIsSuccessful('Test that /fr/news-items history shows');
    }

    /**
     * @dataProvider generateNewsItemIds
     */
    public function testShowSingleItem(int $newsItemId)
    {
        self::ensureKernelShutdown();
        $client = $this->getClientAuthenticated();

        $client->request('GET', "/fr/news-items/{$newsItemId}");

        $this->assertResponseIsSuccessful('test that single news item page loads successfully');
    }

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

        $news = new NewsItem();

        $news->setContent('test content');
        $news->setTitle('Title');
        $news->setStartDate(new \DateTimeImmutable('yesterday'));

        $em->persist($news);
        $em->flush();

        static::$toDelete[] = [NewsItem::class, $news];

        self::ensureKernelShutdown();

        yield [$news->getId()];
    }
}
