<?php

namespace App\Modules\VehiclesInVideo\Services;

use App\Facades\Settings;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;

class VehiclesInVideoApiService
{
    private const DEFAULT_BASE_URL = 'https://api.dev.vehiclesinvideo.com/api/v1';

    private ?Client $client;

    public function __construct(?Client $client = null)
    {
        $this->client = $client;
    }

    private function client(): Client
    {
        if ($this->client === null) {
            $this->client = new Client([
                'headers' => [
                    'api-key' => $this->apiKey(),
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                ],
                'http_errors' => false,
                'timeout' => 60,
                'connect_timeout' => 30,
            ]);
        }

        return $this->client;
    }

    public function requestGrantUrl(string $callbackUrl): array
    {
        $response = $this->client()->get($this->url('/auth/tokens/url'), [
            'query' => [
                'callback_url' => $callbackUrl,
                'client_id' => $this->clientId(),
            ],
        ]);

        return $this->parseResponse($response);
    }

    public function refreshToken(string $refreshToken): array
    {
        $response = $this->client()->post($this->url('/auth/tokens/refresh'), [
            'headers' => [
                'Authorization' => 'Bearer ' . $refreshToken,
            ],
            'json' => [
                'refresh_token' => $refreshToken,
            ],
        ]);

        return $this->parseResponse($response);
    }

    public function sendVideo(string $authToken, array $data): array
    {
        $response = $this->client()->post($this->url('/videos/send'), [
            'headers' => [
                'Authorization' => 'Bearer ' . $authToken,
            ],
            'json' => $data,
        ]);

        return $this->parseResponse($response);
    }

    private function url(string $path): string
    {
        return rtrim($this->baseUrl(), '/') . $path;
    }

    private function baseUrl(): string
    {
        return Settings::get('vehicles-in-video-base-url') ?: self::DEFAULT_BASE_URL;
    }

    private function apiKey(): ?string
    {
        return Settings::get('vehicles-in-video-api-key');
    }

    private function clientId(): ?string
    {
        return Settings::get('vehicles-in-video-client-id');
    }

    private function parseResponse(ResponseInterface $response): array
    {
        $statusCode = $response->getStatusCode();
        $body = (string) $response->getBody();

        if ($body === '') {
            return ['status_code' => $statusCode];
        }

        $decoded = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error('VehiclesInVideo: Invalid JSON response', [
                'status' => $statusCode,
                'body' => $body,
                'json_error' => json_last_error_msg(),
            ]);

            return [
                'status_code' => $statusCode,
                'error' => ['message' => 'Invalid JSON response from API'],
            ];
        }

        $decoded['status_code'] = $statusCode;

        return $decoded;
    }
}
