<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;

class RapidNSE implements NSEService
{
    /**
     * Fetch all stocks from the Nairobi Stock Exchange RapidAPI.
     *
     * @return array<int, mixed> Decoded JSON response (list of stocks)
     */
    public function getStocks(): array
    {
        if (! $this->isConfigured()) {
            return [];
        }

        $url = $this->baseUrl().'/stocks';
        try {
            $response = Http::connectTimeout(3)
                ->timeout(8)
                ->withHeaders($this->headers())
                ->get($url);

            if (! $response->successful()) {
                Log::warning('RapidNSE API request failed', [
                    'endpoint' => 'stocks',
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                $response->throw();
            }

            return $response->json() ?? [];
        } catch (ConnectionException|RequestException|Throwable $e) {
            Log::warning('RapidNSE stocks request failed', [
                'endpoint' => 'stocks',
                'message' => $e->getMessage(),
            ]);

            return [];
        }
    }

    /**
     * Fetch stock data by symbol from the Nairobi Stock Exchange RapidAPI.
     *
     * @param  string  $symbol  Stock symbol as expected by the API (e.g. "Safaricom")
     * @return array<string, mixed> Decoded JSON response
     */
    public function getStock(string $symbol): array
    {
        if (! $this->isConfigured()) {
            return [];
        }

        $url = $this->baseUrl().'/stocks/'.trim($symbol);
        try {
            $response = Http::connectTimeout(3)
                ->timeout(8)
                ->withHeaders($this->headers())
                ->get($url);

            if (! $response->successful()) {
                Log::warning('RapidNSE API request failed', [
                    'symbol' => $symbol,
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                $response->throw();
            }

            return $response->json() ?? [];
        } catch (ConnectionException|RequestException|Throwable $e) {
            Log::warning('RapidNSE stock request failed', [
                'symbol' => $symbol,
                'message' => $e->getMessage(),
            ]);

            return [];
        }
    }

    /**
     * @return array<string, string>
     */
    private function headers(): array
    {
        $host = config('services.rapidapi_nse.host');
        $key = config('services.rapidapi_nse.key');

        return [
            'x-rapidapi-host' => $host,
            'x-rapidapi-key' => $key,
        ];
    }

    private function baseUrl(): string
    {
        return 'https://'.config('services.rapidapi_nse.host');
    }

    private function isConfigured(): bool
    {
        $host = (string) config('services.rapidapi_nse.host');
        $key = (string) config('services.rapidapi_nse.key');

        return $host !== '' && $key !== '';
    }
}
