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

class VoiceSessionModel {
  final String id;
  final String? websocketUrl;
  final String status;
  final String? startedAt;
  final String? endedAt;

  const VoiceSessionModel({
    required this.id,
    this.websocketUrl,
    required this.status,
    this.startedAt,
    this.endedAt,
  });

  factory VoiceSessionModel.fromJson(Map<String, dynamic> json) {
    return VoiceSessionModel(
      id: json['id'] as String? ?? json['sessionId'] as String? ?? '',
      websocketUrl: json['websocket_url'] as String? ??
          json['ws_url'] as String? ??
          json['websocketUrl'] as String?,
      status: json['status'] as String? ?? 'active',
      startedAt: json['startedAt'] as String? ??
          json['started_at'] as String? ??
          json['createdAt'] as String? ??
          json['created_at'] as String?,
      endedAt: json['endedAt'] as String? ?? json['ended_at'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      if (websocketUrl != null) 'websocket_url': websocketUrl,
      'status': status,
      if (startedAt != null) 'startedAt': startedAt,
      if (endedAt != null) 'endedAt': endedAt,
    };
  }

  /// Converts this model to a domain [VoiceSession] entity.
  VoiceSession toEntity() {
    return VoiceSession(
      id: id,
      websocketUrl: websocketUrl,
      status: _parseStatus(status),
      startedAt: DateTime.tryParse(startedAt ?? '') ?? DateTime.now(),
      endedAt: endedAt != null ? DateTime.tryParse(endedAt!) : null,
    );
  }

  static VoiceSessionStatus _parseStatus(String status) {
    switch (status.toLowerCase()) {
      case 'ringing':
        return VoiceSessionStatus.ringing;
      case 'connecting':
        return VoiceSessionStatus.connecting;
      case 'active':
      case 'connected':
        return VoiceSessionStatus.active;
      case 'ended':
      case 'closed':
        return VoiceSessionStatus.ended;
      case 'error':
        return VoiceSessionStatus.error;
      default:
        return VoiceSessionStatus.connecting;
    }
  }
}
