import '../../domain/entities/alert_event.dart';

class AlertEventModel {
  final String id;
  final String? ruleId;
  final String? serverId;
  final String severity;
  final String? message;
  final bool acknowledged;
  final String? createdAt;

  const AlertEventModel({
    required this.id,
    this.ruleId,
    this.serverId,
    required this.severity,
    this.message,
    required this.acknowledged,
    this.createdAt,
  });

  factory AlertEventModel.fromJson(Map<String, dynamic> json) {
    return AlertEventModel(
      id: json['id']?.toString() ?? '',
      ruleId: json['ruleId'] as String? ?? json['rule_id'] as String?,
      serverId:
          json['serverId'] as String? ?? json['server_id'] as String?,
      severity: json['severity'] as String? ?? 'info',
      message: json['message'] as String?,
      acknowledged: json['acknowledged'] as bool? ?? false,
      createdAt:
          json['createdAt'] as String? ?? json['created_at'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      if (ruleId != null) 'ruleId': ruleId,
      if (serverId != null) 'serverId': serverId,
      'severity': severity,
      if (message != null) 'message': message,
      'acknowledged': acknowledged,
    };
  }

  /// Converts this model to a domain [AlertEvent] entity.
  AlertEvent toEntity() {
    return AlertEvent(
      id: id,
      ruleId: ruleId,
      serverId: serverId,
      severity: severity,
      message: message,
      acknowledged: acknowledged,
      createdAt: _parseDateTime(createdAt),
    );
  }

  /// Creates a model from a domain [AlertEvent] entity.
  factory AlertEventModel.fromEntity(AlertEvent entity) {
    return AlertEventModel(
      id: entity.id,
      ruleId: entity.ruleId,
      serverId: entity.serverId,
      severity: entity.severity,
      message: entity.message,
      acknowledged: entity.acknowledged,
      createdAt: entity.createdAt?.toIso8601String(),
    );
  }

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