<?php

namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class DvlaService
{
    private const API_URL = 'https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles';

    public function __construct(
        private readonly string $apiKey
    ) {
    }

    public function getVehicleDetails(string $registrationNumber): ?array
    {
        $response = $this->client()->post(self::API_URL, [
            'registrationNumber' => $registrationNumber,
        ]);

        if ($response->successful()) {
            return $response->json();
        }

        if ($response->status() === 404) {
            return null;
        }

        $response->throw();
    }

    private function client(): PendingRequest
    {
        return Http::withHeaders([
            'x-api-key' => $this->apiKey,
            'Content-Type' => 'application/json',
        ])->timeout(30);
    }
}
