<?php

declare(strict_types=1);

namespace Pesisportaali\Services;

use RuntimeException;

final class PesisApi
{
    public function get(string $endpoint): array
    {
        $endpoint = ltrim($endpoint, '/');
        $separator = str_contains($endpoint, '?') ? '&' : '?';

        $url =
            'https://api.pesistulokset.fi/api/v1/public/' .
            $endpoint .
            $separator .
            'apikey=' .
            urlencode(PESIS_API_KEY);

        $ch = curl_init($url);

        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
            CURLOPT_ENCODING => '',
            CURLOPT_HTTPHEADER => [
                'X-API-Key: ' . PESIS_API_KEY,
                'Accept: application/json, text/plain, */*',
                'User-Agent: Mozilla/5.0 Pesisportaali/1.0',
                'Referer: https://www.pesistulokset.fi/',
            ],
        ];

        $outgoingIp = defined('PESIS_OUTGOING_IP')
            ? (string)PESIS_OUTGOING_IP
            : '37.27.162.86';

        if ($outgoingIp !== '') {
            $options[CURLOPT_INTERFACE] = $outgoingIp;
        }

        curl_setopt_array($ch, $options);

        $body = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);

        curl_close($ch);

        if ($body === false || $status !== 200) {
            throw new RuntimeException(
                'Pesistulokset API: HTTP ' .
                $status .
                ($error !== '' ? ' – ' . $error : '')
            );
        }

        $data = json_decode($body, true);

        if (!is_array($data)) {
            throw new RuntimeException(
                'Pesistulokset API ei palauttanut JSON-dataa.'
            );
        }

        return $data;
    }
}
