import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:krow_core/core.dart';

import '../../domain/repositories/place_repository.dart';

class PlaceRepositoryImpl implements PlaceRepository {
  final http.Client _client;

  PlaceRepositoryImpl({http.Client? client}) : _client = client ?? http.Client();

  @override
  Future<List<String>> searchCities(String query) async {
    if (query.isEmpty) return [];

    final Uri uri = Uri.https(
      'maps.googleapis.com',
      '/maps/api/place/autocomplete/json',
      <String, String>{
        'input': query,
        'types': '(cities)',
        'key': AppConfig.googleMapsApiKey,
      },
    );

    try {
      final http.Response response = await _client.get(uri);

      if (response.statusCode == 200) {
        final Map<String, dynamic> data = json.decode(response.body) as Map<String, dynamic>;
        
        if (data['status'] == 'OK' || data['status'] == 'ZERO_RESULTS') {
          final List<dynamic> predictions = data['predictions'] as List<dynamic>;
          
          return predictions.map((dynamic prediction) {
            return prediction['description'] as String;
          }).toList();
        } else {
             // Handle other statuses (OVER_QUERY_LIMIT, REQUEST_DENIED, etc.)
             // Returning empty list for now to avoid crashing UI, ideally log this.
             return [];
        }
      } else {
         throw Exception('Network Error: ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }
}
