<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PlaceAutocompleteController extends Controller
{
    public function autocomplete(Request $request): JsonResponse
    {
        $data = $request->validate([
            'input' => ['required', 'string', 'min:2', 'max:255'],
            'language' => ['nullable', 'string', 'min:2', 'max:10'],
            'country' => ['nullable', 'string', 'size:2'],
            'session_token' => ['nullable', 'string', 'max:255'],
        ]);

        $key = (string) config('services.google_maps.key');
        if ($key === '') {
            return response()->json([
                'message' => 'La cle Google Maps n est pas configuree.',
            ], 503);
        }

        $language = strtolower((string) ($data['language'] ?? 'fr'));
        $country = strtolower((string) ($data['country'] ?? 'fr'));

        $params = [
            'input' => $data['input'],
            'language' => $language,
            'types' => 'address',
            'components' => 'country:' . $country,
            'key' => $key,
        ];

        if (!empty($data['session_token'])) {
            $params['sessiontoken'] = $data['session_token'];
        }

        $response = Http::timeout(10)
            ->acceptJson()
            ->get('https://maps.googleapis.com/maps/api/place/autocomplete/json', $params);

        if (!$response->successful()) {
            return response()->json([
                'message' => 'La requete Google Places a echoue.',
            ], 502);
        }

        $payload = $response->json() ?: [];
        $status = strtoupper((string) ($payload['status'] ?? ''));
        if (!in_array($status, ['OK', 'ZERO_RESULTS'], true)) {
            return response()->json([
                'message' => (string) ($payload['error_message'] ?? 'Google Places a retourne une erreur.'),
                'status' => $status,
            ], 422);
        }

        $predictions = is_array($payload['predictions'] ?? null)
            ? $payload['predictions']
            : [];

        $dataOut = collect($predictions)
            ->map(function (mixed $item): ?array {
                if (!is_array($item)) {
                    return null;
                }

                $description = (string) ($item['description'] ?? '');
                if ($description === '') {
                    return null;
                }

                return [
                    'description' => $description,
                    'place_id' => (string) ($item['place_id'] ?? ''),
                    'main_text' => (string) ($item['structured_formatting']['main_text'] ?? ''),
                    'secondary_text' => (string) ($item['structured_formatting']['secondary_text'] ?? ''),
                ];
            })
            ->filter()
            ->values()
            ->all();

        return response()->json([
            'data' => $dataOut,
        ]);
    }
}
