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

use Chill\MainBundle\Test\PrepareClientTrait;
use Chill\PersonBundle\Entity\SocialWork\Evaluation;
use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

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

    private EntityManagerInterface $em;

    private static ?Evaluation $evaluationToReset = null;

    protected function tearDown(): void
    {
        if (null === self::$evaluationToReset) {
            return;
        }

        self::bootKernel();

        $em = self::getContainer()->get(EntityManagerInterface::class);
        $evaluation = $em->find(Evaluation::class, self::$evaluationToReset->getId());

        $evaluation->setActive(true);
        $em->flush();
    }

    /**
     * @dataProvider dataGenerateSocialActionWithEvaluations
     */
    public function testListEvaluationBySocialAction(SocialAction $action, Evaluation $inactiveEvaluation): void
    {
        $client = $this->getClientAuthenticated();

        $client->request('GET', sprintf('/api/1.0/person/social-work/evaluation/by-social-action/%d.json', $action->getId()));

        $this->assertResponseIsSuccessful();

        $content = json_decode($client->getResponse()->getContent(), true, 512, JSON_THROW_ON_ERROR);

        $ids = array_map(static fn (array $item) => $item['id'], $content['results']);

        $this->assertNotContains($inactiveEvaluation->getId(), $ids);
    }

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

        /** @var SocialAction $socialAction */
        $socialAction = $em->createQuery(
            'SELECT s FROM '.SocialAction::class.' s WHERE SIZE(s.evaluations) >= 2'
        )
            ->setMaxResults(1)
            ->getSingleResult();

        // set the first evaluation as inactive and save
        self::$evaluationToReset = $socialAction->getEvaluations()->first();
        self::$evaluationToReset->setActive(false);

        $em->flush();

        self::ensureKernelShutdown();

        yield [$socialAction, self::$evaluationToReset];
    }
}
