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

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Tests\TestHelper;
use Faker;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class SingleTaskControllerTest extends WebTestCase
{
    /**
     * @var Faker\Generator
     */
    protected $faker;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->faker = Faker\Factory::create('fr');
    }

    public function testNew()
    {
        $client = self::createClient(
            [],
            TestHelper::getAuthenticatedClientOptions()
        );
        $person = $this->getRandomPerson('Center A');

        $crawler = $client->request('GET', '/fr/task/single-task/new', [
            'person_id' => $person->getId(),
        ]);
        var_dump($crawler->text());

        $this->assertTrue($client->getResponse()->isSuccessful());

        $form = $crawler->selectButton('Envoi')->form();

        $title = $this->faker->sentence;
        $circles = $form->get('circle')
            ->availableOptionsValues();

        $client->submit($form, [
            'title' => $title,
            'circle' => $circles[\array_rand($circles)],
        ]);

        $this->assertTrue($client->getResponse()->isRedirect(sprintf(
            '/fr/task/task/list/%d',
            $person->getId()
        )));

        $crawler = $client->followRedirect();

        $this->assertStringContainsString(
            $title,
            $crawler->text(),
            'Assert that newly created task title is shown in list page'
        );
    }

    /**
     * @return \Chill\PersonBundle\Entity\Person
     */
    protected function getRandomPerson(mixed $centerName)
    {
        $em = self::$kernel
            ->getContainer()
            ->get('doctrine.orm.entity_manager');

        $centers = $em
            ->getRepository(Center::class)
            ->findAll();

        $center = \array_filter(
            $centers,
            static fn (Center $c) => $c->getName() === $centerName
        )[0];

        $ids = $em
            ->createQuery(
                'SELECT p.id FROM ChillPersonBundle:Person p '
                .'WHERE p.center = :center'
            )
            ->setParameter('center', $center)
            ->getResult();

        $id = $ids[\array_rand($ids)];

        return self::$kernel
            ->getContainer()
            ->get('doctrine.orm.entity_manager')
            ->getRepository(\Chill\PersonBundle\Entity\Person::class)
            ->find($id);
    }
}
