import '../../domain/entities/terminal_session.dart';
import '../../domain/repositories/terminal_repository.dart';
import '../datasources/terminal_datasource.dart';

class TerminalRepositoryImpl implements TerminalRepository {
  final TerminalDatasource _datasource;

  TerminalRepositoryImpl(this._datasource);

  @override
  Future<TerminalSession> connect(String serverId) async {
    final data = await _datasource.connect(serverId);
    return TerminalSession(
      id: data['id']?.toString() ?? '',
      serverId: data['serverId'] as String? ??
          data['server_id'] as String? ??
          serverId,
      serverName:
          data['serverName'] as String? ?? data['server_name'] as String?,
      connectedAt: _parseDateTime(
          data['connectedAt'] as String? ?? data['connected_at'] as String?),
      status: data['status'] as String? ?? 'connected',
    );
  }

  @override
  Future<void> disconnect(String sessionId) async {
    await _datasource.disconnect(sessionId);
  }

  @override
  Future<List<TerminalSession>> getActiveSessions() async {
    final items = await _datasource.fetchActiveSessions();
    return items
        .map((data) => TerminalSession(
              id: data['id']?.toString() ?? '',
              serverId: data['serverId'] as String? ??
                  data['server_id'] as String?,
              serverName: data['serverName'] as String? ??
                  data['server_name'] as String?,
              connectedAt: _parseDateTime(data['connectedAt'] as String? ??
                  data['connected_at'] as String?),
              status: data['status'] as String? ?? 'connected',
            ))
        .toList();
  }

  static DateTime? _parseDateTime(String? value) {
    if (value == null) return null;
    return DateTime.tryParse(value);
  }
}
