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

/// Remote datasource for fetching dashboard data from the IT0 backend.
class DashboardDatasource {
  final Dio _dio;

  DashboardDatasource(this._dio);

  /// Fetches the list of servers and their statuses.
  Future<List<Map<String, dynamic>>> fetchServers() async {
    final response = await _dio.get(ApiEndpoints.servers);
    final data = response.data;
    if (data is List) return data.cast<Map<String, dynamic>>();
    if (data is Map && data.containsKey('items')) {
      return (data['items'] as List).cast<Map<String, dynamic>>();
    }
    return [];
  }

  /// Fetches alert events for computing alert summary.
  Future<List<Map<String, dynamic>>> fetchAlertEvents() async {
    final response = await _dio.get(ApiEndpoints.alertEvents);
    final data = response.data;
    if (data is List) return data.cast<Map<String, dynamic>>();
    if (data is Map && data.containsKey('items')) {
      return (data['items'] as List).cast<Map<String, dynamic>>();
    }
    return [];
  }

  /// Fetches recent operations tasks with an optional limit.
  Future<List<Map<String, dynamic>>> fetchRecentOps({int limit = 5}) async {
    final response = await _dio.get(
      ApiEndpoints.opsTasks,
      queryParameters: {'limit': limit},
    );
    final data = response.data;
    if (data is List) return data.cast<Map<String, dynamic>>();
    if (data is Map && data.containsKey('items')) {
      return (data['items'] as List).cast<Map<String, dynamic>>();
    }
    return [];
  }
}
