<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class AddressSearchController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $validated = $request->validate(['q' => ['required', 'string', 'min:3', 'max:200']]);

        $response = Http::withHeaders([
            'User-Agent' => config('app.name').' ('.config('app.url').')',
        ])->get('https://nominatim.openstreetmap.org/search', [
            'q' => $validated['q'],
            'format' => 'json',
            'addressdetails' => 1,
            'limit' => 6,
            'countrycodes' => 'us,ca',
        ]);

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

        /** @var list<array<string, mixed>> $payload */
        $payload = $response->json();

        $results = collect($payload)->map(fn ($item) => [
            'label' => $item['display_name'],
            'street' => trim(($item['address']['house_number'] ?? '').' '.($item['address']['road'] ?? '')),
            'city' => $item['address']['city']
                        ?? $item['address']['town']
                        ?? $item['address']['village']
                        ?? $item['address']['municipality']
                        ?? '',
            'postal' => $item['address']['postcode'] ?? '',
        ])->filter(fn ($r) => $r['street'] && $r['city'])->values();

        return response()->json($results);
    }
}
