<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use RuntimeException;

class GoogleMapsService
{
    private const METERS_PER_MILE = 1609.344;

    private readonly ?string $apiKey;

    public function __construct(?string $apiKey = null)
    {
        $this->apiKey = $apiKey ?? config('services.google_maps.key');
    }

    /**
     * Resolve the driving distance and duration between two points using the
     * Distance Matrix API — one call handles "one route, many vehicle types"
     * far better than the old project's per-vehicle-type Directions API loop.
     *
     * @return array{distance: float, duration_minutes: int}
     */
    public function distanceAndDuration(string $origin, string $destination, string $unit = 'mi'): array
    {
        if (! $this->apiKey) {
            throw new RuntimeException('GOOGLE_MAPS_API_KEY is not configured.');
        }

        $response = Http::get('https://maps.googleapis.com/maps/api/distancematrix/json', [
            'origins' => $origin,
            'destinations' => $destination,
            'units' => $unit === 'km' ? 'metric' : 'imperial',
            'key' => $this->apiKey,
        ]);

        $response->throw();

        $element = $response->json('rows.0.elements.0');

        if (! $element || $element['status'] !== 'OK') {
            throw new RuntimeException('Could not calculate distance for the given addresses.');
        }

        $meters = $element['distance']['value'];
        $seconds = $element['duration']['value'];

        return [
            'distance' => round($unit === 'km' ? $meters / 1000 : $meters / self::METERS_PER_MILE, 2),
            'duration_minutes' => (int) ceil($seconds / 60),
        ];
    }
}
