import 'package:get/get.dart';
import 'package:sigap/src/cores/services/supabase_service.dart';
import 'package:sigap/src/features/daily-ops/data/models/models/unit_statistics_model.dart';
import 'package:sigap/src/utils/exceptions/exceptions.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

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

  final _supabase = SupabaseService.instance.client;

  // Get statistics for a specific unit
  Future<List<UnitStatisticModel>> getUnitStatistics(String codeUnit) async {
    try {
      final statistics = await _supabase
          .from('unit_statistics')
          .select()
          .eq('code_unit', codeUnit)
          .order('year', ascending: false)
          .order('month', ascending: false);
      
      return statistics.map((stat) => UnitStatisticModel.fromJson(stat)).toList();
    } on PostgrestException catch (error) {
      throw TExceptions.fromCode(error.code ?? 'unknown_error');
    } catch (e) {
      throw TExceptions('Failed to fetch unit statistics: ${e.toString()}');
    }
  }

  // Get statistics for a specific year
  Future<List<UnitStatisticModel>> getUnitStatisticsByYear(String codeUnit, int year) async {
    try {
      final statistics = await _supabase
          .from('unit_statistics')
          .select()
          .eq('code_unit', codeUnit)
          .eq('year', year)
          .order('month');
      
      return statistics.map((stat) => UnitStatisticModel.fromJson(stat)).toList();
    } on PostgrestException catch (error) {
      throw TExceptions.fromCode(error.code ?? 'unknown_error');
    } catch (e) {
      throw TExceptions('Failed to fetch unit statistics: ${e.toString()}');
    }
  }

  // Get statistics for a specific month and year
  Future<UnitStatisticModel> getUnitStatisticByMonthYear(String codeUnit, int month, int year) async {
    try {
      final statistic = await _supabase
          .from('unit_statistics')
          .select()
          .eq('code_unit', codeUnit)
          .eq('month', month)
          .eq('year', year)
          .single();
      
      return UnitStatisticModel.fromJson(statistic);
    } on PostgrestException catch (error) {
      throw TExceptions.fromCode(error.code ?? 'unknown_error');
    } catch (e) {
      throw TExceptions('Failed to fetch unit statistic: ${e.toString()}');
    }
  }

  // Get latest statistics for all units
  Future<List<UnitStatisticModel>> getLatestStatisticsForAllUnits() async {
    try {
      // This would need a custom RPC function in Supabase to get the latest statistic for each unit
      final statistics = await _supabase.rpc('get_latest_unit_statistics');
      
      return statistics.map((stat) => UnitStatisticModel.fromJson(stat)).toList();
    } on PostgrestException catch (error) {
      throw TExceptions.fromCode(error.code ?? 'unknown_error');
    } catch (e) {
      throw TExceptions('Failed to fetch latest statistics: ${e.toString()}');
    }
  }

  // Get total statistics summarized by year
  Future<List<Map<String, dynamic>>> getTotalStatisticsByYear(int year) async {
    try {
      final statistics = await _supabase.rpc('summarize_statistics_by_year', params: {'target_year': year});
      
      return List<Map<String, dynamic>>.from(statistics);
    } on PostgrestException catch (error) {
      throw TExceptions.fromCode(error.code ?? 'unknown_error');
    } catch (e) {
      throw TExceptions('Failed to fetch statistics summary: ${e.toString()}');
    }
  }
}
