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

/// Remote datasource for server operations.
class ServersDatasource {
  final Dio _dio;

  ServersDatasource(this._dio);

  /// Fetches all servers, optionally filtered by environment or status.
  Future<List<ServerModel>> fetchAll({
    String? environment,
    String? status,
  }) async {
    final queryParams = <String, dynamic>{};
    if (environment != null) queryParams['environment'] = environment;
    if (status != null) queryParams['status'] = status;

    final response = await _dio.get(
      ApiEndpoints.servers,
      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) => ServerModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  /// Fetches a single server by ID.
  Future<ServerModel> fetchById(String id) async {
    final response = await _dio.get('${ApiEndpoints.servers}/$id');
    return ServerModel.fromJson(response.data as Map<String, dynamic>);
  }
}
