import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/cores/services/supabase_service.dart';
import 'package:sigap/src/features/map/data/models/models/cities_model.dart';

class CitiesRepository extends GetxController {
  static CitiesRepository get instance => Get.find();

  final _supabase = SupabaseService.instance.client;
  final _log = Get.find<Logger>();

  // Cache cities to reduce database calls
  final RxList<CityModel> _citiesCache = <CityModel>[].obs;

  // Get all cities
  Future<List<CityModel>> getAllCities() async {
    try {
      // If cache exists, return it
      if (_citiesCache.isNotEmpty) {
        return _citiesCache;
      }

      final response = await _supabase
          .from('cities')
          .select('*, districts(*), units(*)')
          .order('name');

      final data = response as List;
      final cities = data.map((json) => CityModel.fromJson(json)).toList();

      // Update cache
      _citiesCache.value = cities;
      return cities;
    } catch (e) {
      _log.e('Error fetching cities: $e');
      throw Exception('Failed to load cities: $e');
    }
  }

  // Get city by ID
  Future<CityModel> getCityById(String cityId) async {
    try {
      // Check cache first
      final cachedCity = _citiesCache.firstWhereOrNull(
        (city) => city.id == cityId,
      );
      if (cachedCity != null) {
        return cachedCity;
      }

      final response =
          await _supabase
              .from('cities')
              .select('*, districts(*), units(*)')
              .eq('id', cityId)
              .single();

      return CityModel.fromJson(response);
    } catch (e) {
      _log.e('Error fetching city $cityId: $e');
      throw Exception('Failed to load city details: $e');
    }
  }

  // Get default city (Jember)
  Future<CityModel> getDefaultCity() async {
    try {
      final response =
          await _supabase
              .from('cities')
              .select('*, districts(*), units(*)')
              .eq('name', 'Jember')
              .single();

      return CityModel.fromJson(response);
    } catch (e) {
      _log.e('Error fetching default city: $e');
      throw Exception('Failed to load default city: $e');
    }
  }

  // Clear cache
  void clearCache() {
    _citiesCache.clear();
  }
}
