/// Repository pour la gestion des logs et du monitoring système
/// Interface avec l'API backend LogsMonitoringResource
library logs_monitoring_repository;

import 'package:injectable/injectable.dart';
import 'package:unionflow_mobile_apps/core/network/api_client.dart';
import '../models/system_log_model.dart';
import '../models/system_metrics_model.dart';
import '../models/system_alert_model.dart';

abstract class LogsMonitoringRepository {
  Future<List<SystemLogModel>> searchLogs({
    String? level,
    String? source,
    String? searchQuery,
    String? timeRange,
  });
  Future<SystemMetricsModel> getMetrics();
  Future<List<SystemAlertModel>> getAlerts();
  Future<void> acknowledgeAlert(String alertId);
}

@LazySingleton(as: LogsMonitoringRepository)
class LogsMonitoringRepositoryImpl implements LogsMonitoringRepository {
  final ApiClient _apiClient;

  LogsMonitoringRepositoryImpl(this._apiClient);

  List<dynamic> _parseListResponse(dynamic data) {
    if (data is List) return data;
    if (data is Map && data.containsKey('content')) {
      final content = data['content'];
      return content is List ? content : [];
    }
    return [];
  }

  @override
  Future<List<SystemLogModel>> searchLogs({
    String? level,
    String? source,
    String? searchQuery,
    String? timeRange,
  }) async {
    final response = await _apiClient.post(
      '/api/logs/search',
      data: {
        'level': level ?? 'TOUS',
        'source': source ?? 'TOUS',
        'searchQuery': searchQuery,
        'timeRange': timeRange ?? 'Dernières 24h',
        'page': 0,
        'pageSize': 100,
      },
    );
    if (response.statusCode == 200) {
      final data = _parseListResponse(response.data);
      return data
          .map((e) => SystemLogModel.fromJson(e as Map<String, dynamic>))
          .toList();
    }
    throw Exception('Erreur ${response.statusCode}');
  }

  @override
  Future<SystemMetricsModel> getMetrics() async {
    final response = await _apiClient.get('/api/monitoring/metrics');
    if (response.statusCode == 200) {
      return SystemMetricsModel.fromJson(response.data as Map<String, dynamic>);
    }
    throw Exception('Erreur ${response.statusCode}');
  }

  @override
  Future<List<SystemAlertModel>> getAlerts() async {
    final response = await _apiClient.get('/api/alerts');
    if (response.statusCode == 200) {
      final data = _parseListResponse(response.data);
      return data
          .map((e) => SystemAlertModel.fromJson(e as Map<String, dynamic>))
          .toList();
    }
    throw Exception('Erreur ${response.statusCode}');
  }

  @override
  Future<void> acknowledgeAlert(String alertId) async {
    final response = await _apiClient.post('/api/alerts/$alertId/acknowledge');
    if (response.statusCode != 200) {
      throw Exception('Erreur ${response.statusCode}');
    }
  }
}
