<?php
declare(strict_types=1);

final class NabzClient {
    public function __construct(
        private string $apiKey,
        private string $baseUrl = 'https://nabzebazaar.ir/api/v1'
    ) {}

    public function get(string $path, array $query = []): array {
        $url = rtrim($this->baseUrl, '/') . $path;
        if ($query) $url .= '?' . http_build_query($query);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['X-API-Key: ' . $this->apiKey, 'Accept: application/json'],
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 30,
        ]);
        $raw = curl_exec($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        if ($raw === false) throw new RuntimeException('Network error: ' . $curlError);
        $body = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
        if ($status < 200 || $status >= 300 || empty($body['success'])) {
            $error = $body['error'] ?? [];
            throw new RuntimeException($status . ' ' . ($error['code'] ?? 'API_ERROR') . ': ' . ($error['message'] ?? 'Request failed'));
        }
        return $body;
    }

    public function latest(array $filters = []): array { return $this->get('/prices/latest', $filters); }
    public function history(string $productId, int $days = 7, string $interval = 'day'): array {
        return $this->get('/prices/history', ['product_id'=>$productId,'days'=>$days,'interval'=>$interval]);
    }
    public function usage(): array { return $this->get('/usage'); }
}

// $client = new NabzClient('YOUR_API_KEY');
// $result = $client->latest(['brand'=>'Samsung','storage_gb'=>128]);
