import 'package:firebase_database/firebase_database.dart';
import 'package:syncrow_web/pages/analytics/services/realtime_device_service/realtime_device_service.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';

class FirebaseRealtimeDeviceService implements RealtimeDeviceService {
  @override
  Stream<List<Status>> subscribe(String deviceId) {
    try {
      final ref = FirebaseDatabase.instance.ref('device-status/$deviceId');

      return ref.onValue.asyncMap((event) {
        final data = event.snapshot.value as Map<dynamic, dynamic>?;

        if (data == null || data['status'] == null) {
          throw Exception('Invalid data received from Firebase');
        }

        final statusMap = data['status'] as List<dynamic>;
        return statusMap.map((status) {
          if (status is! Map<dynamic, dynamic>) {
            throw Exception('Invalid status format');
          }

          return Status(
            code: status['code']?.toString() ?? '',
            value: status['value']?.toString() ?? '',
          );
        }).toList();
      });
    } catch (e) {
      throw Exception('Error subscribing to device status: $e');
    }
  }
}
