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

use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class CustomFieldsGroupControllerTest extends WebTestCase
{
    /**
     * @doesNotPerformAssertions
     */
    public function testCompleteScenario()
    {
        self::bootKernel(['environment' => 'test_customizable_entities_test_not_empty_config']);
        // Create a new client to browse the application
        $client = self::createClient([], [
            'PHP_AUTH_USER' => 'admin',
            'PHP_AUTH_PW' => 'olala',
        ]);

        // create the entity
        $this->createCustomFieldsGroup($client);

        // Edit the entity
        $this->editCustomFieldsGroup($client);
    }

    private function createCustomFieldsGroup(Client &$client)
    {
        // Create a new entry in the database
        $crawler = $client->request('GET', '/fr/admin/customfieldsgroup/');

        $this->assertEquals(
            200,
            $client->getResponse()->getStatusCode(),
            'Unexpected HTTP status code for GET /customfieldsgroup/'
        );

        $crawler = $client->click($crawler->selectLink('Créer un nouveau groupe')->link());

        // Fill in the form and submit it
        $form = $crawler->selectButton('Créer')->form([
            'custom_fields_group[name][fr]' => 'Test',
            'custom_fields_group[entity]' => \Chill\PersonBundle\Entity\Person::class,
        ]);

        $crawler = $client->submit($form);

        $crawler = $client->followRedirect();

        // Check data in the show view
        $this->assertGreaterThan(
            0,
            $crawler->filter('td:contains("Test")')->count(),
            'Missing element td:contains("Test")'
        );
    }

    private function editCustomFieldsGroup(Client $client)
    {
        $crawler = $client->request('GET', '/fr/admin/customfieldsgroup/');
        $links = $crawler->selectLink('Modifier');

        $this->assertGreaterThan(
            0,
            $links->count(),
            "We can't find a 'Modifier' link on the index page"
        );
        $crawler = $client->click($links->last()->link());

        $this->assertEquals(200, $client->getResponse()->getStatusCode());

        $form = $crawler->selectButton('Mettre à jour')->form([
            'custom_fields_group[name][fr]' => 'Foo',
        ]);

        $client->submit($form);
        $crawler = $client->followRedirect();

        // Check the element contains an attribute with value equals "Foo"
        $this->assertGreaterThan(
            0,
            $crawler->filter('[value="Foo"]')->count(),
            'Missing element [value="Foo"]'
        );
    }
}
