<?php

declare(strict_types=1);

namespace App\Tests\Functional\Controller;

use App\Module\Core\Domain\Entity\User;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 */
final class ShareSearchTest extends WebTestCase
{
    public function testSearchRequiresAuthentication(): void
    {
        $client = self::createClient();
        $client->request('GET', '/api/share/search?q=rapport');

        self::assertSame(401, $client->getResponse()->getStatusCode());
    }

    public function testSearchReturnsEmptyForShortQuery(): void
    {
        $client = self::createClient();
        $this->login($client);

        $client->request('GET', '/api/share/search?q=a');

        self::assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertSame('a', $data['query']);
        self::assertSame([], $data['entries']);
    }

    public function testSearchReturns409WhenNotConfigured(): void
    {
        $client = self::createClient();
        $this->login($client);

        $client->request('GET', '/api/share/search?q=rapport');

        self::assertSame(409, $client->getResponse()->getStatusCode());
    }

    private function login(KernelBrowser $client): void
    {
        $em   = self::getContainer()->get('doctrine.orm.entity_manager');
        $user = $em->getRepository(User::class)->findOneBy(['username' => 'alice']);
        $client->loginUser($user);
    }
}
