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

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

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

    /**
     * @dataProvider generateRandomAddress
     */
    public function testGetGeographicalUnitCoveringAddress(int $addressId): void
    {
        $client = $this->getClientAuthenticated();

        $client->request('GET', '/api/1.0/main/geographical-unit/by-address/'.$addressId.'.json');

        $this->assertResponseIsSuccessful();
    }

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

        $nb = $em->createQuery('SELECT COUNT(a) FROM '.Address::class.' a')->getSingleScalarResult();
        /** @var Address $random */
        $random = $em->createQuery('SELECT a FROM '.Address::class.' a')
            ->setFirstResult(random_int(0, $nb))
            ->setMaxResults(1)
            ->getSingleResult();

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