<?php

namespace App\Services;

use App\Master\Models\CapVehicle;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AutoGrabVehicleLookupService
{
    protected string $endpoint;
    protected string $apiKey;

    public function __construct()
    {
        $this->endpoint = config('services.autograb.endpoint');
        $this->apiKey = config('services.autograb.api_key');
    }

    public function search(string $query, string $region = 'uk'): ?array
    {
        try {
            $response = Http::withHeaders([
                'ApiKey' => $this->apiKey,
            ])->get("{$this->endpoint}/v2/vehicles", [
                'search' => $query,
                'region' => $region,
            ]);

            if ($response->failed()) {
                Log::warning('AutoGrab API search failed', [
                    'status' => $response->status(),
                    'query' => $query,
                ]);
                return null;
            }

            return $response->json();
        } catch (\Exception $e) {
            Log::warning('AutoGrab API search exception', [
                'message' => $e->getMessage(),
                'query' => $query,
            ]);
            return null;
        }
    }

    public function buildSearchQuery(CapVehicle $vehicle): string
    {
        $year = $this->resolveYear($vehicle);
        $parts = array_filter([
            $year,
            $vehicle->manufacturer,
            $vehicle->short_model,
            $vehicle->short_derivative,
        ]);

        return preg_replace('/\s+/', ' ', trim(implode(' ', $parts)));
    }

    /**
     * @return string[]
     */
    public function getVehicleIds(CapVehicle $vehicle): array
    {
        $query = $this->buildSearchQuery($vehicle);
        $response = $this->search($query);

        if (empty($response['vehicles'])) {
            return [];
        }

        return collect($response['vehicles'])
            ->pluck('id')
            ->filter()
            ->map(fn ($id) => (string) $id)
            ->values()
            ->all();
    }

    protected function resolveYear(CapVehicle $vehicle): ?int
    {
        if ($vehicle->derivative_introduced_year) {
            if ($vehicle->derivative_discontinued_year) {
                return (int) round(
                    ($vehicle->derivative_introduced_year + $vehicle->derivative_discontinued_year) / 2
                );
            }
            return $vehicle->derivative_introduced_year;
        }

        if ($vehicle->model_introduced) {
            if ($vehicle->model_discontinued) {
                return (int) round(
                    ($vehicle->model_introduced + $vehicle->model_discontinued) / 2
                );
            }
            return $vehicle->model_introduced;
        }

        return null;
    }
}
