// src/services/geolocation_service.dart
import 'package:geolocator/geolocator.dart';

class SimplePosition {
  final double latitude;
  final double longitude;
  final DateTime timestamp;

  SimplePosition({
    required this.latitude,
    required this.longitude,
    required this.timestamp,
  });
}

class GeolocationService {
  static Future<bool> isLocationServiceEnabled() async {
    return await Geolocator.isLocationServiceEnabled();
  }

  static Future<LocationPermission> checkPermission() async {
    return await Geolocator.checkPermission();
  }

  static Future<LocationPermission> requestPermission() async {
    return await Geolocator.requestPermission();
  }

  static Future<bool> hasPermission() async {
    LocationPermission permission = await Geolocator.checkPermission();
    return permission == LocationPermission.always ||
        permission == LocationPermission.whileInUse;
  }

  static Future<SimplePosition?> getCurrentLocation() async {
    try {
      bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) return null;

      LocationPermission permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.denied) {
        permission = await Geolocator.requestPermission();
        if (permission == LocationPermission.denied) return null;
      }

      if (permission == LocationPermission.deniedForever) return null;

      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.low,
        timeLimit: const Duration(seconds: 5),
      );

      return SimplePosition(
        latitude: position.latitude,
        longitude: position.longitude,
        timestamp: position.timestamp,
      );
    } catch (e) {
      print('Error: $e');
      return null;
    }
  }

  static Future<SimplePosition?> getCurrentLocationWithRetry({int maxRetries = 2}) async {
    for (int i = 0; i < maxRetries; i++) {
      final position = await getCurrentLocation();
      if (position != null) return position;
      if (i < maxRetries - 1) await Future.delayed(const Duration(seconds: 1));
    }
    return null;
  }
}