import 'package:get/get.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/logger.dart';

class AuditLogController extends GetxController {
  var logs = <Map<String, dynamic>>[].obs;
  var isLoading = true.obs;
  var currentPage = 1.obs;
  var totalPages = 1.obs;
  var selectedFilter = 'all'.obs;

  @override
  void onInit() {
    super.onInit();
    fetchLogs();
  }

  Future<void> fetchLogs({int page = 1}) async {
    try {
      isLoading.value = true;
      final params = <String, dynamic>{'page': page, 'limit': 30};
      
      if (selectedFilter.value != 'all') {
        params['entity_type'] = selectedFilter.value;
      }

      final res = await DioClient().client.get('audit-log', queryParameters: params);
      if (res.data['success'] == true) {
        final data = res.data['data'];
        if (page == 1) {
          logs.value = List<Map<String, dynamic>>.from(data['logs'] ?? []);
        } else {
          logs.addAll(List<Map<String, dynamic>>.from(data['logs'] ?? []));
        }
        currentPage.value = data['pagination']?['page'] ?? 1;
        totalPages.value = data['pagination']?['pages'] ?? 1;
      }
    } catch (e) {
      AppLogger.error('Failed to fetch audit logs', e);
    } finally {
      isLoading.value = false;
    }
  }

  void loadMore() {
    if (currentPage.value < totalPages.value) {
      fetchLogs(page: currentPage.value + 1);
    }
  }

  void applyFilter(String filter) {
    selectedFilter.value = filter;
    fetchLogs();
  }
}
