<?php

namespace App\Tests\Service;

use App\Service\EntrepriseSearchService;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class EntrepriseSearchServiceTest extends TestCase
{
    public function testSearchTooShortQuery(): void
    {
        $httpClient = $this->createStub(HttpClientInterface::class);
        $service = new EntrepriseSearchService($httpClient);

        $response = $service->search('a');
        $data = json_decode($response->getContent(), true);

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame([], $data['results']);
        $this->assertSame(0, $data['total_results']);
    }

    public function testSearchEmptyQuery(): void
    {
        $httpClient = $this->createStub(HttpClientInterface::class);
        $service = new EntrepriseSearchService($httpClient);

        $response = $service->search('');
        $this->assertSame(200, $response->getStatusCode());
    }

    public function testSearchSuccess(): void
    {
        $apiResponse = $this->createStub(ResponseInterface::class);
        $apiResponse->method('toArray')->willReturn([
            'results' => [['siren' => '123456789', 'nom_complet' => 'ACME']],
            'total_results' => 1,
        ]);

        $httpClient = $this->createStub(HttpClientInterface::class);
        $httpClient->method('request')->willReturn($apiResponse);

        $service = new EntrepriseSearchService($httpClient);
        $response = $service->search('acme');

        $data = json_decode($response->getContent(), true);
        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame(1, $data['total_results']);
        $this->assertSame('123456789', $data['results'][0]['siren']);
    }

    public function testSearchWithCustomPerPage(): void
    {
        $apiResponse = $this->createStub(ResponseInterface::class);
        $apiResponse->method('toArray')->willReturn(['results' => [], 'total_results' => 0]);

        $httpClient = $this->createMock(HttpClientInterface::class);
        $httpClient->expects($this->once())->method('request')
            ->with('GET', $this->anything(), $this->callback(fn ($opts) => 5 === $opts['query']['per_page']))
            ->willReturn($apiResponse);

        $service = new EntrepriseSearchService($httpClient);
        $service->search('test', 5);
    }

    public function testSearchApiError(): void
    {
        $httpClient = $this->createStub(HttpClientInterface::class);
        $httpClient->method('request')->willThrowException(new \RuntimeException('Network error'));

        $service = new EntrepriseSearchService($httpClient);
        $response = $service->search('test');

        $data = json_decode($response->getContent(), true);
        $this->assertSame(502, $response->getStatusCode());
        $this->assertSame('Service indisponible', $data['error']);
    }
}
