import 'package:equatable/equatable.dart';

enum EventLevel { debug, info, warning, error, fatal }

enum EventType {
  pageView,
  userAction,
  apiCall,
  performance,
  error,
  crash,
  session,
  presence,
}

class TelemetryEvent extends Equatable {
  final String eventId;
  final EventType type;
  final EventLevel level;
  final String name;
  final Map<String, dynamic>? properties;
  final DateTime timestamp;
  final String? userId;
  final String? sessionId;
  final String installId;
  final String deviceContextId;

  const TelemetryEvent({
    required this.eventId,
    required this.type,
    required this.level,
    required this.name,
    this.properties,
    required this.timestamp,
    this.userId,
    this.sessionId,
    required this.installId,
    required this.deviceContextId,
  });

  factory TelemetryEvent.fromJson(Map<String, dynamic> json) {
    return TelemetryEvent(
      eventId: json['eventId'] as String,
      type: EventType.values.firstWhere(
        (e) => e.name == json['type'],
        orElse: () => EventType.userAction,
      ),
      level: EventLevel.values.firstWhere(
        (e) => e.name == json['level'],
        orElse: () => EventLevel.info,
      ),
      name: json['name'] as String,
      properties: json['properties'] as Map<String, dynamic>?,
      timestamp: DateTime.parse(json['timestamp'] as String),
      userId: json['userId'] as String?,
      sessionId: json['sessionId'] as String?,
      installId: json['installId'] as String,
      deviceContextId: json['deviceContextId'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'eventId': eventId,
      'type': type.name,
      'level': level.name,
      'name': name,
      'properties': properties,
      'timestamp': timestamp.toIso8601String(),
      'userId': userId,
      'sessionId': sessionId,
      'installId': installId,
      'deviceContextId': deviceContextId,
    };
  }

  /// 转换为服务端 API 格式（Amplitude 风格：设备字段提升为顶层独立列）
  Map<String, dynamic> toServerJson() {
    final props = Map<String, dynamic>.from(properties ?? {});
    final deviceBrand = props.remove('device_brand');
    final deviceModel = props.remove('device_model');
    final deviceOs = props.remove('device_os');
    final appVersion = props.remove('app_version');
    final locale = props.remove('locale');

    return {
      'eventName': name,
      'userId': userId,
      'installId': installId,
      'clientTs': timestamp.millisecondsSinceEpoch ~/ 1000,
      'deviceBrand': deviceBrand,
      'deviceModel': deviceModel,
      'deviceOs': deviceOs,
      'appVersion': appVersion,
      'locale': locale,
      'properties': {
        ...props,
        'eventId': eventId,
        'type': type.name,
        'level': level.name,
        'sessionId': sessionId,
        'deviceContextId': deviceContextId,
      },
    };
  }

  @override
  List<Object?> get props => [eventId, type, level, name, properties, timestamp, userId, sessionId, installId, deviceContextId];
}
