<?php

namespace App\Service;

use Symfony\Contracts\HttpClient\HttpClientInterface;

// Founit un accès à l’API Overpass
class OverpassClient
{
    public function __construct(
        private HttpClientInterface $client,
    ) {
    }

    public function query($query, $prefix = '[out:json][timeout:60];', $suffix = 'out geom;')
    {
        $response = $this->client->request('GET', 'https://overpass-api.de/api/interpreter', [
            'query' => [
                'data' => $prefix.$query.$suffix,
            ],
        ]);

        $isStatusCodeOk = (200 === $response->getStatusCode());
        $isContentTypeJson = ('application/json' === $response->getHeaders()['content-type'][0]);

        if (!$isStatusCodeOk or !$isContentTypeJson) {
            throw new \RuntimeException();
        }

        return $response->getContent();
    }

    public function rawQuery($query)
    {
        $response = $this->client->request('GET', 'https://overpass-api.de/api/interpreter', [
            'query' => [
                'data' => $query,
            ],
        ]);

        $isStatusCodeOk = (200 === $response->getStatusCode());

        if (!$isStatusCodeOk) {
            throw new \RuntimeException();
        }

        return $response->getContent();
    }
}
