import 'dart:convert';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';

import '../model/user_role_model.dart';

class UserRoleRepo {
  Future<List<UserRoleModel>> getAllUserRole() async {
    List<UserRoleModel> allUser = [];
    final currentUser = FirebaseAuth.instance.currentUser;

    if (currentUser == null || currentUser.uid.isEmpty) {
      throw Exception('User not authenticated');
    }

    final path = '${currentUser.uid}/User Role';

    try {
      final snapshot = await FirebaseDatabase.instance.ref(path).get();

      if (snapshot.exists) {
        for (var element in snapshot.children) {
          try {
            var data = UserRoleModel.fromJson(jsonDecode(jsonEncode(element.value)));
            allUser.add(data);
          } catch (e) {
            print('Error parsing user role: $e');
          }
        }
      }
      return allUser;
    } catch (e) {
      print('Error fetching user roles: $e');
      rethrow;
    }
  }

  // Future<List<UserRoleModel>> getAllUserRole(String userId) async {
  //   List<UserRoleModel> allUser = [];
  //
  //   try {
  //     final snapshot = await FirebaseDatabase.instance.ref(userId).child('User Role').orderByKey().get();
  //
  //     if (snapshot.exists) {
  //       for (var element in snapshot.children) {
  //         try {
  //           var data = UserRoleModel.fromJson(jsonDecode(jsonEncode(element.value)));
  //           data.userKey = element.key;
  //           allUser.add(data);
  //         } catch (e) {
  //           debugPrint('Error parsing user role: $e');
  //         }
  //       }
  //     }
  //     return allUser;
  //   } catch (e) {
  //     debugPrint('Error fetching user roles: $e');
  //     rethrow; // or return empty list if appropriate
  //   }
  // }

  Future<List<UserRoleModel>> getAllUserRoleFromAdmin() async {
    List<UserRoleModel> allUser = [];

    await FirebaseDatabase.instance.ref('Admin Panel').child('User Role').orderByKey().get().then((value) {
      for (var element in value.children) {
        var data = UserRoleModel.fromJson(jsonDecode(jsonEncode(element.value)));
        allUser.add(data);
      }
    });
    return allUser;
  }
}
