<?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\Household\Household;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;

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

    private ?KernelBrowser $client = null;

    protected function setUp(): void
    {
        $this->client = $this->getClientAuthenticated();
    }

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

    /**
     * @dataProvider generateValidHouseholdIds
     */
    public function testAddresses(mixed $householdId)
    {
        $this->client->request(
            Request::METHOD_GET,
            "/fr/person/household/{$householdId}/addresses"
        );

        $this->assertResponseIsSuccessful();
    }

    /**
     * @dataProvider generateValidHouseholdIds
     */
    public function testAddressMove(mixed $householdId)
    {
        $this->client->request(
            Request::METHOD_GET,
            "/fr/person/household/{$householdId}/address/move"
        );

        $this->assertResponseIsSuccessful();

        // ici, il faudrait tester la requête POST
    }

    /**
     * @dataProvider generateValidHouseholdIds
     */
    public function testEditMetadata(mixed $householdId)
    {
        $crawler = $this->client->request(
            Request::METHOD_GET,
            "/fr/person/household/{$householdId}/summary",
            [
                'edit' => true,
            ]
        );

        $this->assertResponseIsSuccessful();

        $form = $crawler->filter('#form_household_comment_confirm')
            ->form();

        $form['household[commentMembers][comment]'] = 'This is a text **generated** by automatic tests';
        $form['household[waitingForBirth]']->tick();
        $form['household[waitingForBirthDate]'] = (new \DateTime('today'))
            ->add(new \DateInterval('P10M'))->format('Y-m-d');

        $this->client->submit($form);
        $response = $this->client->getResponse();

        self::assertEquals(302, $response->getStatusCode());
        self::assertEquals("/fr/person/household/{$householdId}/summary", $response->headers->get('Location'));
    }

    /**
     * @dataProvider generateValidHouseholdIds
     */
    public function testSummary(mixed $householdId)
    {
        $this->client->request(
            Request::METHOD_GET,
            "/fr/person/household/{$householdId}/summary"
        );

        $this->assertResponseIsSuccessful();
    }

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

        $ids = $em->createQuery(
            sprintf('SELECT DISTINCT h.id FROM %s h JOIN h.members m JOIN m.person p JOIN p.centerHistory ch JOIN ch.center c WHERE c.name = :center AND ch.endDate IS NULL', Household::class)
        )
            ->setParameter('center', 'Center A')
            ->setMaxResults(100)
            ->getScalarResult();

        if ([] === $ids) {
            throw new \RuntimeException('no household ids with center "Center A"');
        }

        \shuffle($ids);

        yield [\array_pop($ids)['id']];

        yield [\array_pop($ids)['id']];

        yield [\array_pop($ids)['id']];

        self::ensureKernelShutdown();
    }
}
