<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class EntrepriseSearchService
{
    private const API_URL = 'https://recherche-entreprises.api.gouv.fr/search';

    public function __construct(
        private HttpClientInterface $httpClient,
    ) {
    }

    public function search(string $query, int $perPage = 10): JsonResponse
    {
        if (\strlen($query) < 2) {
            return new JsonResponse(['results' => [], 'total_results' => 0]);
        }

        try {
            $response = $this->httpClient->request('GET', self::API_URL, [
                'query' => [
                    'q' => $query,
                    'page' => 1,
                    'per_page' => $perPage,
                ],
            ]);

            return new JsonResponse($response->toArray());
        } catch (\Throwable) {
            return new JsonResponse(['results' => [], 'total_results' => 0, 'error' => 'Service indisponible'], 502);
        }
    }
}
