import 'package:get/get.dart';
import 'package:sigap/src/cores/services/supabase_service.dart';
import 'package:sigap/src/utils/exceptions/exceptions.dart';

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

  final _supabase = SupabaseService.instance.client;

  Future<List<Map<String, dynamic>>> getActivePanicSessions() async {
    try {
      final response = await _supabase
          .from('incident_logs')
          .select('*, location_id(*), panic_button_logs!inner(*)')
          .eq('status', 'active')
          .order('time', ascending: false);

      return List<Map<String, dynamic>>.from(response);
    } catch (e) {
      throw TExceptions(
        'Failed to fetch active panic sessions: ${e.toString()}',
      );
    }
  }

  Future<Map<String, dynamic>> getPanicSessionById(String id) async {
    try {
      final response =
          await _supabase
              .from('incident_logs')
              .select(
                '*, location_id(*), panic_button_logs!inner(*), evidence(*)',
              )
              .eq('id', id)
              .single();

      return response;
    } catch (e) {
      throw TExceptions(
        'Failed to fetch panic session details: ${e.toString()}',
      );
    }
  }

  Future<bool> checkActivePanicSession() async {
    try {
      final user = SupabaseService.instance.currentUser;
      if (user == null) return false;

      final response =
          await _supabase
              .from('incident_logs')
              .select('id')
              .eq('user_id', user.id)
              .eq('status', 'active')
              .eq('source', 'panic_button')
              .maybeSingle();

      return response != null;
    } catch (e) {
      print('Failed to check active panic session: $e');
      return false;
    }
  }
}
