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

class SessionModel {
  final String id;
  final String? tenantId;
  final String status;
  final String startedAt;
  final String? endedAt;
  final int messageCount;

  const SessionModel({
    required this.id,
    this.tenantId,
    required this.status,
    required this.startedAt,
    this.endedAt,
    this.messageCount = 0,
  });

  factory SessionModel.fromJson(Map<String, dynamic> json) {
    return SessionModel(
      id: json['id'] as String? ?? '',
      tenantId: json['tenantId'] as String? ?? json['tenant_id'] as String?,
      status: json['status'] as String? ?? 'active',
      startedAt: json['startedAt'] as String? ??
          json['started_at'] as String? ??
          json['created_at'] as String? ??
          json['createdAt'] as String? ??
          DateTime.now().toIso8601String(),
      endedAt: json['endedAt'] as String? ?? json['ended_at'] as String?,
      messageCount: json['messageCount'] as int? ??
          json['message_count'] as int? ??
          0,
    );
  }

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

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

  /// Creates a model from a domain [ChatSession] entity.
  factory SessionModel.fromEntity(ChatSession entity) {
    return SessionModel(
      id: entity.id,
      tenantId: entity.tenantId,
      status: entity.status,
      startedAt: entity.startedAt.toIso8601String(),
      endedAt: entity.endedAt?.toIso8601String(),
      messageCount: entity.messageCount,
    );
  }
}
