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

class ApprovalModel {
  final String id;
  final String? taskId;
  final String? taskDescription;
  final String? command;
  final String? riskLevel;
  final String? requestedBy;
  final String status;
  final String? expiresAt;
  final String? createdAt;

  const ApprovalModel({
    required this.id,
    this.taskId,
    this.taskDescription,
    this.command,
    this.riskLevel,
    this.requestedBy,
    required this.status,
    this.expiresAt,
    this.createdAt,
  });

  factory ApprovalModel.fromJson(Map<String, dynamic> json) {
    return ApprovalModel(
      id: json['id']?.toString() ?? '',
      taskId: json['taskId'] as String? ?? json['task_id'] as String?,
      taskDescription: json['taskDescription'] as String? ??
          json['task_description'] as String?,
      command: json['command'] as String?,
      riskLevel:
          json['riskLevel'] as String? ?? json['risk_level'] as String?,
      requestedBy: json['requestedBy'] as String? ??
          json['requested_by'] as String?,
      status: json['status'] as String? ?? 'pending',
      expiresAt:
          json['expiresAt'] as String? ?? json['expires_at'] as String?,
      createdAt:
          json['createdAt'] as String? ?? json['created_at'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      if (taskId != null) 'taskId': taskId,
      if (taskDescription != null) 'taskDescription': taskDescription,
      if (command != null) 'command': command,
      if (riskLevel != null) 'riskLevel': riskLevel,
      if (requestedBy != null) 'requestedBy': requestedBy,
      'status': status,
    };
  }

  /// Converts this model to a domain [Approval] entity.
  Approval toEntity() {
    return Approval(
      id: id,
      taskId: taskId,
      taskDescription: taskDescription,
      command: command,
      riskLevel: riskLevel,
      requestedBy: requestedBy,
      status: status,
      expiresAt: _parseDateTime(expiresAt),
      createdAt: _parseDateTime(createdAt),
    );
  }

  /// Creates a model from a domain [Approval] entity.
  factory ApprovalModel.fromEntity(Approval entity) {
    return ApprovalModel(
      id: entity.id,
      taskId: entity.taskId,
      taskDescription: entity.taskDescription,
      command: entity.command,
      riskLevel: entity.riskLevel,
      requestedBy: entity.requestedBy,
      status: entity.status,
      expiresAt: entity.expiresAt?.toIso8601String(),
      createdAt: entity.createdAt?.toIso8601String(),
    );
  }

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