<?php
final class NumberHub {
    public function __construct(
        private string $apiKey,
        private string $baseUrl = 'https://api.numberhub.io/v1'
    ) {
        if ($apiKey === '') throw new InvalidArgumentException('apiKey is required');
        $this->baseUrl = rtrim($baseUrl, '/');
    }

    private function request(
        string $method,
        string $path,
        ?array $body = null,
        ?string $idempotencyKey = null
    ): array {
        $ch = curl_init($this->baseUrl . $path);
        $headers = ['Authorization: Bearer ' . $this->apiKey];
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
        ]);
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
        }
        if ($idempotencyKey !== null && $idempotencyKey !== '') {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $raw = curl_exec($ch);
        if ($raw === false) throw new RuntimeException(curl_error($ch));
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);
        $data = json_decode($raw, true) ?: [];
        if ($status < 200 || $status >= 300) {
            throw new RuntimeException($data['message'] ?? $data['error'] ?? "HTTP $status", $status);
        }
        return $data;
    }

    public function balance(): array { return $this->request('GET', '/balance'); }
    public function services(): array { return $this->request('GET', '/services'); }
    public function countries(string $service): array {
        return $this->request('GET', '/countries?service=' . rawurlencode($service));
    }
    public function buyNumber(
        string $service,
        string $country,
        array $options = [],
        ?string $idempotencyKey = null
    ): array {
        return $this->request(
            'POST',
            '/numbers',
            array_merge(compact('service', 'country'), $options),
            $idempotencyKey
        );
    }
    public function getNumber(int $id): array { return $this->request('GET', "/numbers/$id"); }
    public function webhooks(): array { return $this->request('GET', '/webhooks'); }
    public function createWebhook(string $url, array $events = ['order.*']): array {
        return $this->request('POST', '/webhooks', compact('url', 'events'));
    }
    public function testWebhook(int $id): array { return $this->request('POST', "/webhooks/$id/test"); }
    public function deleteWebhook(int $id): array { return $this->request('DELETE', "/webhooks/$id"); }
}
