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

/// Remote datasource for terminal session management.
class TerminalDatasource {
  final Dio _dio;

  TerminalDatasource(this._dio);

  /// Connects to a server terminal session.
  Future<Map<String, dynamic>> connect(String serverId) async {
    final response = await _dio.post(
      ApiEndpoints.wsTerminal,
      data: {'serverId': serverId},
    );
    return response.data as Map<String, dynamic>;
  }

  /// Disconnects from a terminal session.
  Future<void> disconnect(String sessionId) async {
    await _dio.delete('${ApiEndpoints.wsTerminal}/$sessionId');
  }

  /// Fetches all active terminal sessions.
  Future<List<Map<String, dynamic>>> fetchActiveSessions() async {
    final response = await _dio.get('${ApiEndpoints.wsTerminal}/sessions');

    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.cast<Map<String, dynamic>>();
  }
}
