<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\Location\Geocoder;
use Illuminate\Support\Facades\Log;

class LocationController extends Controller
{
    public function suggest(Request $request, Geocoder $geo)
    {
        // accept ?q=… or the "location" field (handy for htmx on the input)
        $q = trim($request->input('q', $request->input('location', '')));

        // short queries: return empty list (avoid rate limits)
        if ($q === '' || mb_strlen($q) < 3) {
            return response()->view('event.partials.suggestions', [
                'suggestions' => [],
            ]);
        }

        try {
            // pass the current user so the geocoder can bias by zip/centroid
            // signature: suggestions(string $query, int $limit = 5, ?User $user = null)
            $suggestions = $geo->suggestions($q, 5, $request->user());
        } catch (\Throwable $e) {
            Log::warning('location suggest failed', ['q' => $q, 'error' => $e->getMessage()]);
            $suggestions = [];
        }

        return view('event.partials.suggestions', [
            'suggestions' => $suggestions,
        ]);
    }
}
