<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GeocodingService
{
    public function buildQuery(array $data): ?string
    {
        $parts = array_filter([
            $data['address'] ?? null,
            $data['territory_city'] ?? null,
            $data['territory_state'] ?? null,
            $data['postal_code'] ?? null,
            $data['territory_country'] ?? null,
        ], function ($v) {
            return is_string($v) && trim($v) !== '';
        });

        return count($parts) ? implode(', ', $parts) : null;
    }

    public function geocode(?string $query, ?string $franchiseDomainForLog = null): ?array
    {
        $query = trim((string) $query);
        if ($query === '') {
            return null;
        }

        $key = config('services.google_maps.key');

        if (!$key) {
            Log::error('Geocode failed: GOOGLE_MAPS_KEY missing');
            return null;
        }

        try {
            $res = Http::timeout(10)->get(
                'https://maps.googleapis.com/maps/api/geocode/json',
                [
                    'address' => $query,
                    'key' => $key,
                ]
            );

            if (!$res->ok()) {
                Log::error('Geocode HTTP not OK', ['status' => $res->status(), 'query' => $query]);
                return null;
            }

            $data = $res->json();

            if (($data['status'] ?? null) !== 'OK') {
                Log::error('Geocode API non-OK', [
                    'google_status' => $data['status'] ?? null,
                    'query' => $query,
                ]);
                return null;
            }

            $loc = $data['results'][0]['geometry']['location'] ?? null;

            if (!$loc || !isset($loc['lat'], $loc['lng'])) {
                Log::error('Geocode missing lat/lng', ['query' => $query]);
                return null;
            }

            return [
                'lat' => (float) $loc['lat'],
                'lng' => (float) $loc['lng'],
            ];
        } catch (\Exception $e) {
            Log::error('Geocode exception', ['error' => $e->getMessage(), 'query' => $query]);
            return null;
        }
    }
}
