import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../models/alert_event_model.dart';

/// Remote datasource for alert event operations.
class AlertsDatasource {
  final Dio _dio;

  AlertsDatasource(this._dio);

  /// Fetches all alert events, optionally filtered by severity.
  Future<List<AlertEventModel>> fetchAll({String? severity}) async {
    final queryParams = <String, dynamic>{};
    if (severity != null) queryParams['severity'] = severity;

    final response = await _dio.get(
      ApiEndpoints.alertEvents,
      queryParameters: queryParams.isNotEmpty ? queryParams : null,
    );

    final data = response.data;
    List<dynamic> items;

    if (data is List) {
      items = data;
    } else if (data is Map && data.containsKey('items')) {
      items = data['items'] as List;
    } else {
      items = [];
    }

    return items
        .map((item) =>
            AlertEventModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  /// Acknowledges an alert event by ID.
  Future<AlertEventModel> acknowledge(String id) async {
    final response =
        await _dio.post('${ApiEndpoints.alertEvents}/$id/acknowledge');
    return AlertEventModel.fromJson(
        response.data as Map<String, dynamic>);
  }
}
